[leetcode] Climbing Stairs

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.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

分析:爬楼梯问题,经典的动态规划问题。每次爬楼梯只能爬一阶或两阶,要求计算n个台阶有几种爬法。显然,当前状态与前面的状态有关,因此使用动态规划法。
维护一个数组dp,dp[i]表示爬到第i个台阶的方法。我们以4个台阶为例:
第1个台阶:dp[1]=1;
第2个台阶:有两种方法,第一种先上第一个,再上第二个;第二种直接上两个台阶,于是:dp[2]=dp[1]+1=2;
第3个台阶:有两种方法,第一种从第一个台阶上两步;第二种从第二个台阶上一步,于是:dp[3] = dp[1]+dp[2];
第4个台阶:同理,dp[4] = dp[3]+dp[2];
于是我们得到状态转移方程:dp[i] = dp[i-1]+dp[i-2]。(i>2)
整理代码如下:
 1 class Solution {
 2     public int climbStairs(int n) {
 3         if ( n == 1 ) return 1;
 4         int[] dp = new int[n+1];
 5         dp[1]=1;
 6         dp[2]=2;
 7         for ( int i = 3 ; i <= n ; i ++ ){
 8             dp[i] = dp[i-1]+dp[i-2];
 9         }
10         return dp[n];
11     }
12 }

      运行时间2ms。

猜你喜欢

转载自www.cnblogs.com/boris1221/p/9314325.html