Algorithm: Climb Stairs

来源:互联网 发布:centos 7 安装 编辑:程序博客网 时间:2024/05/22 00:31

Question:

 

If you are only able to climb some stairs with 1,2 or 3 steps in each time, how many possibilities you have when you climb 10 stairs? Please display all the possibilities.

 

Codes:

 

 

Analysis:

1. We need a array to store each count of step we move. Obviously, the max of the array size should be the length of stairs. In my example, the array is step[].

2. We also need a var to mark the position of step[] so that we can know what time we have moved.

3. Var Count is used to record how many possibilities we have got in totally.

4. Now see func climb(N):

Suppose that we climbed 1 step in first time. Then, we can store 1 to the step[0]. Obviously, index is 0 at here. After that we still have N-1 steps need to climb. So, we have to invoke recursion which is stated as climb(N-1) to repeat these operations. 

However, what if we want to climb 2 steps or 3 steps in first time?  In order to travel all the possibilities, we have to go back to previous step and re-climb with the number of new step. Base on this idea, we can make index=index-1 to go back to previous step and store 2 or 3 to step[index]  and keep index moving with index++. Likewise, we need to invoke climb(N-1) to climb the rest of steps.

At last, when the steps we have climbed is 0, that means we have already finished to climb. So we can stop recursion invoking and output array step to display one of Moving Solution. Since this is a recursion calling, we will get all the possibilities.

 

Result:

原创粉丝点击