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 }
Please call me JiangYouDang!