第十六周LeetCode

来源:互联网 发布:福州广电网络 编辑:程序博客网 时间:2024/05/22 17:34

题目
Climbing Stairs
难度 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?

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

实现思路

可以用动态规划实现。因为每次只能走一步或两步,设dp[i]为走第i阶楼梯时的可选走法数,则dp[i]取决于dp[i-1]和dp[i-2],即如果走一步到达dp[i]就有dp[i-1]种走法,走两步到达dp[i]就有dp[i-2]种走法,因此dp[i]=dp[i-1]+dp[i-2].由该状态转移方程可知需要先初始化dp[0]和dp[1]。

实现代码

    int climbStairs(int n) {        //one_step表示前一步的可选走法数量,two_step表示前两步的可选走法数量        int one_step = 1, two_step = 1;        int steps = 0;        if (n == 0 || n == 1) return 1;        for (int i = 2; i <= n; i++) {            steps = one_step+two_step;            two_step = one_step;            one_step = steps;        }        return steps;    }
原创粉丝点击