码迷,mamicode.com
首页 > 其他好文 > 详细

Climbing Stairs

时间:2014-11-12 16:24:33      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   java   sp   for   div   

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处理的

Climbing Stairs

标签:style   blog   io   color   ar   java   sp   for   div   

原文地址:http://www.cnblogs.com/luckygxf/p/4092424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!