http://oj.leetcode.com/problems/climbing-stairs/
这是一个很有意思的爬楼梯问题,一开始我是按照中学时候的方法进行排列组合计算。
比如对于一个5层的楼梯,最多需要5步,最少需要3步, 如果step = 3,则有一个两步的,两个一步的,
共有 C(3,1)种走法,在 [3, 5]这个范围内按照这个算法计算即可,但是计算排列的时候导致整形溢出
之后采用递归的方法,发生TLE错误。
最后,发现, 返回结果与n 存在 Fibonacci数列 的关系. 问题得以解决
AC:Fibonacci数列
class Solution {
public:
int climbStairs(int n) {
int prev0 = 1;
int prev1 = 1;
for(int i =2; i <= n; i++) {
int tmp = prev0 + prev1;
prev0 = prev1;
prev1 = tmp;
}
return prev1;
}
};
WA: 递归方法导致TLE错误
class Solution {
public:
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 1)
return 1;
if (n == 2)
return 2;
//first take 1 step
int first1 = climbStairs(n- 1);
//first take 2 step
int first2 = climbStairs(n-2);
return first1 + first2;
}
};
WA: 排列组合方法导致溢出 比如35排列15个:118528911546113729396736000000L
class Solution {
public:
int climbStairs(int n) {
int max_steps = n;
int min_steps = n/2 + n%2;
int single_steps = n/2;
int result = 0;
for(int i = min_steps; i <= max_steps ; i++) {
result += assemble(i, single_steps--);
}
return result;
}
int assemble(int total, int choose) {
int result = 1;
if(choose == total || choose == 0) return result;
for(int i = total; i > total-choose; i--) result *= i;
for(int i = choose; i >=1; i--) result /= i;
return result;
}
};