1. 程式人生 > >LeetCode 70:Climbing Stairs

LeetCode 70:Climbing Stairs

ria san 選擇 bst post take text 樓梯 csdn

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?

//設f(n)表示爬n階樓梯的不同方法,有兩種選擇:
//1.從第n-1階,前進1步到達第n階。
//2.從第n-2階,前進2步到達第n階;因此有遞推關系f(n)=f(n-1)+f(n-2),這就是一個斐波那契數列
//利用叠代的方法:
class Solution {
public:
	int climbStairs(int n) {
		if (n <= 2)  return n;
		else
		{
			int *f = new int[n];
			f[0] = 1; //一個臺階的方法為1
			f[1] = 2; //兩個臺階的方法為2

			for (int i = 2; i < n; i++)
			{
				f[i] = f[i - 1] + f[i - 2];
			}
			return f[n - 1]; //f[n-1]即n個臺階的方法
		}
	}
};

技術分享

LeetCode 70:Climbing Stairs