您的位置:首页 > 大数据 > 人工智能

LeetCode-70. Climbing Stairs

2018-01-04 19:08 387 查看
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?

Note: Given n will be a positive integer.

例子

Input: 2

Output: 2

Explanation: There are two ways to climb to the top.

1 step + 1 step

2 steps

Input: 3

Output: 3

Explanation: There are three ways to climb to the top.

1 step + 1 step + 1 step

1 step + 2 steps

2 steps + 1 step

分析

这题的解法有很多,因为我是在集中做DP的题目,所以这里只给出一种动态规划思想的解法。

我们用一个长度为n+1的一维数组来保存爬到n层的共有多少种方法。由给出的例子可知爬1层只有1种方法,爬2层有2种方法,爬3层就是在1层再一次性爬2层的方法数与在2层再一次性爬1层的方法数之和,由此可以推出爬n层就是爬n-2层的方法数与爬n-1层的方法数之和,从而得到递推式dp
=dp[n-2]+dp[n-1]。

实现

class Solution {
public int climbStairs(int n) {
if(n==1)
return 1;
int[] dp=new int[n+1];
dp[1]=1;
dp[2]=2;
for(int i=3;i<=n;++i)
{
dp[i]=dp[i-1]+dp[i-2];
}
return dp
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态规划 LeetCode