zoukankan      html  css  js  c++  java
  • 70. 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

    Solution1:递归
    class Solution {
        public int climbStairs(int n) {
            if(n==1){
                return 1;
            }
            else if(n==2){
                return 2;
            }
            else{
                return climbStairs(n-2) + climbStairs(n-1);
            }
            
        }
    }

    但是运行显示 Time limited exceed.

    网上大佬说是因为递归的效率太低,会产生很多分支,所以放弃使用递归。

    Solution2:

    class Solution {
        public int climbStairs(int n) {
           if(n<=1){
               return 1;
           }
            else{
                int[] dp = new int[n];
                dp[0] = 1;
                dp[1] = 2;
                for(int i = 2; i < n; i++){
                    dp[i] = dp[i-1] + dp[i-2];
                }
                return dp[n-1];
            }
        }
    }

    这个方法使用了Dynamic Programming提高效率。来自Grandyang大佬。

    solution3

    “我们可以对空间进行进一步优化,我们只用两个整型变量a和b来存储过程值,首先将a+b的值赋给b,然后a赋值为原来的b,所以应该赋值为b-a即可。这样就模拟了上面累加的过程,而不用存储所有的值,参见代码如下:”

    我去这是什么神仙方法,

    public class Solution {
        public int climbStairs(int n) {
            int a = 1, b = 1;
            while (n-- > 0) {
                b += a; 
                a = b - a;
            }
            return a;
        }
    }

     附递归和动态规划算法题目详解:

    http://www.cnblogs.com/DarrenChan/p/8734203.html#_label1

    3. 迭代,和求Fibonacci数列第n项一样,每次把prev和cur向右移一位

    class Solution {
     public int climbStairs(int n) {
         int cur = 1;
         int prev = 0;
         for(int i = 1; i <= n; i++){
             int tmp = cur;
             cur += prev;
             prev = tmp;
         }
         return cur;
        }
    }
  • 相关阅读:
    TASK1
    CSS再学
    Html再学
    Python的hasattr() getattr() setattr() 函数使用方法详解
    GET/POST/g和钩子函数(hook)
    cookie和session
    SQLAlchemy外键的使用
    jquery树形菜单插件treeView
    linux设置防火墙
    linux解压命令
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10201202.html
Copyright © 2011-2022 走看看