• Climbing Stairs


    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?

     1 import java.math.BigInteger;
     2 
     3 public class Solution {
     4     public int climbStairs(int n) {
     5         int num2s = n / 2;
     6         int ways = 0;
     7         int num1s = n - num2s * 2;
     8         for(int i = num2s; i >= 0; i--){
     9             ways += selectMFromN(num2s + num1s, num2s);
    10             num2s--;
    11             num1s += 2;
    12         }
    13         return ways;
    14     }
    15     /**
    16      * 计算C(N,M) = n * (n - 1) *...(n - m + 1) / m!
    17      * @param n
    18      * @param m
    19      * @return
    20      */
    21     public int selectMFromN(int n, int m){
    22         BigInteger fenzi = new BigInteger("1");
    23         BigInteger fenmu = new BigInteger("1");
    24         for(int i = n ; i >= n - m + 1;i--){
    25             fenzi = fenzi.multiply(new BigInteger(String.valueOf(i)));
    26         }
    27         for(int i = m ; i >= 1;i--){
    28             fenmu = fenmu.multiply(new BigInteger(String.valueOf(i)));
    29         }
    30         return (fenzi.divide(fenmu)).intValue();
    31     }
    32 }

    这里要求C(N,M)有溢出,我用BigInteger处理的

    ps:用斐波拉契数列实现,或者动态规划DP

     1 public class Solution {
     2     public int climbStairs(int n) {
     3         if(0 == n)
     4             return 0;
     5         if(1 == n)
     6             return 1;
     7         int pre = 1;
     8         int current = 1;
     9         
    10         for(int i = 2; i <= n; i++){
    11             int temp = pre + current;
    12             pre = current;
    13             current = temp;
    14         }
    15         
    16         return current;
    17     }
    18     
    19 }

     用DP确实计算量要小,效率更高

     1 public class Solution {
     2     public int climbStairs(int n) {
     3         int steps[] = new int[n + 1];
     4         for(int i = 0; i <= n; i++){
     5             if(0 == i || 1 == i)
     6                 steps[i] = 1;
     7             else{
     8                 steps[i] = steps[i - 1] + steps[i - 2];
     9             }
    10         }
    11         return steps[n];
    12     }
    13 }
  • 相关阅读:
    1.13 开源软件是什么?有哪些?
    1.10 Linux桌面环境(桌面系统)大比拼[附带优缺点
    Bracket Seuence deletion (找规律,2个元素分别分析一下)
    web学习笔记
    计算机结构 week2
    Alice and the Cake (CF1654C 模拟题,逆续想法)
    star MST (dp)
    For gamers. BY GAMERS (dp预处理+二分)
    Preorder (树贡献问题, 这题关键重复情况的如何判断)
    python 笔记
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4092424.html
Copyright © 2020-2023  润新知