您的位置:首页 > 大数据 > 人工智能

【LeetCode】(70)Climbing Stairs (Easy)

2015-08-22 20:24 429 查看

题目


Climbing Stairs

Total Accepted: 65108 Total
Submissions: 189441My Submissions

Question
Solution

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?

解析

最简单的思路就是用递归,然而这种题目常常递归会出错,超过次数。

直观的方法就是迭代,其实也很简单

class Solution {
public:
int climbStairs(int n) {
<span style="white-space:pre">		</span>if (n == 1)
<span style="white-space:pre">	</span> return 1;
if (n == 2)
return 2;

vector<int> stNum(n);
stNum[0] = 1;
stNum[1] = 2;

for (int i = 2; i<n; i++)
{
stNum[i] = stNum[i-1] + stNum[i-2];
}
return stNum.back();
}
};


不过还是需要使用一个vector的存储空间,可以更有效的降低空间。

class Solution {
public:
int climbStairs(int n) {
<span style="white-space:pre">		</span>if (n == 1)
return 1;
if (n == 2)
return 2;

int stNum0 = 1;
int stNum1 = 2;
int tmp;
for (int i = 2;i<n;i++)
{
tmp = stNum1;
stNum1 = stNum0 + stNum1;
stNum0 = tmp;
}
return stNum1;
}
};


大神提供了一个使用数学公式的方法



class Solution {
public:
int climbStairs(int n) {
<span style="white-space:pre">	</span>const double s = sqrt(5);
<span style="white-space:pre">	</span>return floor((pow((1+s)/2, n+1) + pow((1-s)/2, n+1))/s + 0.5);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: