天天看点

Leetcode-70. 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?

Subscribe to see which companies asked this question

看到题目我们第一反应就是利用递归的思想,所以我的第一个版本的代码如下:

class Solution {
public:
	int climbStairs(int n) {
		if (n == 0)return 0;
		else if (n == 1)return 1;
		else if (n == 2)return 2;
		else return climbStairs(n-1) + climbStairs(n-2);
	}
};
           

这种情况下当n=4的时候运行超时,很明显,我们可以用空间来换时间。每当我们得到一个n的结果的时候就将它保存到容器re中,当下次需要用到某个n的时

候可以直接从容器中取,而无需再利用递归再求一次值。递归求解方程式climbStairs(n)=climbStairs(n-1) + climbStairs(n-2);其实也是动态规划的思想;改进

之后的代码如下:

class Solution {
public:
	int climbStairs(int n) {
		vector<int>re(n+1,0);
		if (n == 0)return 0;
		else if (n == 1)return 1;
		else if (n == 2)return 2;
		else {
			re[1] = 1;
			re[2] = 2;
			for (int i = 3; i <= n; i++){
				re[i] = re[i - 1] + re[i - 2];
			}
			return re[n];
		}
	}
};
           

运行结果:

Submission Result: Accepted  More Details 

Next challenges:  (H) Wildcard Matching  (H) Palindrome Partitioning II  (M) Android Unlock Patterns

Share your acceptance!

继续阅读