Leetcode ☞ 70. Climbing Stairs

来源:互联网 发布:上海译文出版社淘宝店 编辑:程序博客网 时间:2024/06/16 01:07

70. Climbing Stairs

My Submissions
Total Accepted: 96079 Total Submissions: 265268 Difficulty: Easy

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?








我的AC(0ms,最快):

<span style="font-size:18px;">int climbStairs(int n) {    int ans[n];    ans[0] = 0, ans[1] = 1, ans[2] = 2;    for(int i = 3; i <= n ; i++){        ans[i] = ans[i-1] + ans[i - 2];    }    return ans[n];}</span>
迭代比递归好!

分析:

此题在北邮机试PDF里有,此前已详细看过。动态规划部分。


思路是分治

n的上一状态只有两种情况:1、从n-1跳一层变成n。2、从n-2跳两层变成n  【注意! 不考虑n-2跳两次的情况,因为这不是上一状态,而是上两个状态了!】

每种情况下的走法都只有1种。

因此ans[n] = ans[n-1] + ans[n-2]。 


0 0
原创粉丝点击