首页 > 代码库 > Climbing Stairs

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 n18      * @param m19      * @return20      */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处理的

Climbing Stairs