[Description] There is a number in each stages that indicates the most stages you can leap up. Now, giving an array which represents one kind of stair, please return if you can leap to the last stage, true if ok and vice versa.
e.g. stair[] = {4,3,1,0,2,1,0} return true;
stair[] = {2,1,0,4,3,1,0} return false;
[Thought] think about: what condition it would be true and false in current stair[0]? how to recursively call itself?
[Implementation] C code:
1 #include<stdio.h> 2 3 int leapStage(int stair[], int size) 4 { 5 int i; 6 // if current stage number is zero, false, of course! 7 if(stair[0] == 0) 8 { 9 return 0; 10 } 11 // if current stage number indicate that we can jump over last stage, true. 12 else if(stair[0] >= size-1) 13 { 14 return 1; 15 } 16 // try each way while can't touch the last stages. 17 for(i = stair[0]; i>0; i--) 18 { 19 // if there is one way can do it, true. 20 if(leapStage(stair+i, size-i)) 21 { 22 return 1; 23 } 24 } 25 // after try all the way, can't get it. 26 return 0; 27 } 28 29 int main() 30 { 31 int i; 32 int stair[]={2,1,2,0,3,1,0}; 33 int size=sizeof(stair)/sizeof(stair[0]); 34 for(i=0; i<size; i++) 35 { 36 printf("%d, ",stair[i]); 37 } 38 if(leapStage(stair,size)) 39 { 40 printf(" is true!\n"); 41 } 42 else 43 { 44 printf(" is false!\n"); 45 } 46 }