首页 > 代码库 > [001] leap_stage

[001] leap_stage

[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:

#include<stdio.h>int leapStage(int stair[], int size){        int i;        // if current stage number is zero, false, of course!        if(stair[0] == 0)        {                return 0;        }        // if current stage number indicate that we can jump over last stage, true.        else if(stair[0] >= size-1)        {                return 1;        }        // try each way while can‘t touch the last stages.        for(i = stair[0]; i>0; i--)        {                // if there is one way can do it, true.                if(leapStage(stair+i, size-i))                {                        return 1;                }        }        // after try all the way, can‘t get it.        return 0;}int main(){        int i;        int stair[]={2,1,2,0,3,1,0};        int size=sizeof(stair)/sizeof(stair[0]);        for(i=0; i<size; i++)        {                printf("%d, ",stair[i]);        }        if(leapStage(stair,size))        {                printf(" is true!\n");        }        else        {                printf(" is false!\n");        }}

 

[001] leap_stage