n?1m?0??akm?m,n???akm?m?1,1?m?0,n?0
?akm?m?1,akm?m,n?1??m?0,n?0? (1) 写出递归算法;
(2) 写出非递归算法;
(3) 根据非递归算法,画出求akm(2,1)时栈得变化过程。
解:
unsigned int akm(unsigned int m,unsigned int n) { }
非递归算法:
int akm1(int m,int n) { }
0,akm(2,1) 0 2 1 1,akm(2,0) 6 2 0 2,akm(1,1) 4 1 1 3,akm(1,0) 6 1 0
g=akm(2,0)
akm=akm(m-1,1)=akm(1,1) g=akm(m,n-1)=akm(1,0) akm=akm(m-1,1)=akm(0,1)
Stack s; InitStack(s); ElemType e,e1,d; e、mval=m; Push(s,e); do{
while(e、mval){ }
if(StackLength(s)>1){ }
e1、nval=e、nval; Pop(s,e); e、mval--;
e、nval=e1、nval+1; while(e、nval){ }
e、mval--;
e、nval=1;
e、nval--; Push(s,e);
e、nval=n;
unsigned int g; if(m==0)
return n+1;
if(n==0) return akm(m-1,1); else{ }
g=akm(m,n-1); return akm(m-1,g);
else
}while(StackLength(s)!=1||e、mval!=0); return e、nval+1;
4,akm(0,1) 4 0 1 0,akm(2,1) 0 2 1 1,akm(2,0) 6 2 0 2,akm(1,1) 4 1 1 3,akm(1,0) 6 1 0 0,akm(2,1) 0 2 1 1,akm(2,0) 6 2 0 2,akm(1,1) 4 1 1 3,akm(0,2) 7 0 2 akm=n+1=2 退栈 g=akm(2,0)
akm=akm(m-1,1)=akm(1,1) g=akm(m,n-1)=akm(1,0)
akm=akm(m-1,1)=akm(0,1)=2 退栈 g=akm(2,0)
akm=akm(m-1,1)=akm(1,1)
g=akm(m,n-1)=akm(1,0)=2; akm=akm(m-1,g)=akm(0,2);鏍嘔鷓幗礦雏軛。 akm=n+1=3 退栈 0,akm(2,1) 0 2 1 1,akm(2,0) 6 2 0 2,akm(1,1) 4 1 1
顫莖镝。 0,akm(2,1) 0 2 1 1,akm(2,0) 6 2 0 0,akm(2,1) 0 2 1 1,akm(1,3) 6 1 3 2,akm(1,2) 6 1 2 3,akm(1,1) 6 1 1 4,akm(1,0) 6 1 0 5,akm(0,1) 4 0 1 0,akm(2,1) 0 2 1 1,akm(1,3) 6 1 3 2,akm(1,2) 6 1 2 3,akm(1,1) 6 1 1 4,akm(1,0) 6 1 0 0,akm(2,1) 0 2 1 1,akm(1,3) 6 1 3 2,akm(1,2) 6 1 2 3,akm(1,1) 6 1 1 4,akm(0,2) 7 0 2 0,akm(2,1) 0 2 1 1,akm(1,3) 6 1 3 2,akm(1,2) 6 1 2 3,akm(1,1) 6 1 1 0,akm(2,1) 0 2 1 1,akm(1,3) 6 1 3 2,akm(1,2) 6 1 2 3,akm(0,3) 7 0 3 0,akm(2,1) 0 2 1 1,akm(1,3) 6 1 3 2,akm(1,2) 6 1 2 0,akm(2,1) 0 2 1 1,akm(1,3) 6 1 3
g=akm(2,0)
akm=akm(m-1,1)=akm(1,1)
g=akm(m,n-1)=akm(1,0)=2; akm=akm(m-1,g)=akm(0,2)=3; 退栈肃郧况簡 g=akm(2,0)
akm=akm(m-1,1)=akm(1,1)=3 退栈 g=akm(2,0)=3; akm=akm(1,3) g=akm(1,2); akm(m-1,g) g=akm(1,1); akm(m-1,g) g=akm(1,0); akm(m-1,g) akm=akm(0,1) akm(0,1)=2退栈
g=akm(2,0)=3; akm=akm(1,3) g=akm(1,2); akm(m-1,g) g=akm(1,1); akm(m-1,g) g=akm(1,0); akm(m-1,g) akm=akm(0,1)=2退栈 g=akm(2,0)=3; akm=akm(1,3) g=akm(1,2); akm(m-1,g) g=akm(1,1); akm(m-1,g)
g=akm(1,0)=2; akm(m-1,g)=akm(0,2)鴉厦纤璦緋羅呕。 akm=n+1=3 退栈
g=akm(2,0)=3; akm=akm(1,3) g=akm(1,2); akm(m-1,g) g=akm(1,1); akm(m-1,g)
g=akm(1,0)=2; akm(m-1,g)=akm(0,2)=3退栈冑堅壮攛览個毂。 g=akm(2,0)=3; akm=akm(1,3) g=akm(1,2); akm(m-1,g)
g=akm(1,1)=3; akm(m-1,g)=akm(0,3)讕陨鎮鹫锞蒞轎。 akm=n+1=4 退栈
g=akm(2,0)=3; akm=akm(1,3) g=akm(1,2); akm(m-1,g)
g=akm(1,1)=3; akm(m-1,g)=akm(0,3)=4 退栈織赇饺漣难娄锷。 g=akm(2,0)=3; akm=akm(1,3)
g=akm(1,2)=4; akm(m-1,g)=akm(0,4)龅颠鈹语骧紼秽。