首页 > 其他 > 详细

[001] leap_stage

时间:2014-10-20 18:46:39      阅读:356      评论:0      收藏:0      [点我收藏+]

[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

原文:http://www.cnblogs.com/lyutian/p/4037609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!