Climbing Stairs

512 ワード

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階の階段を登る方法を表す.f(n) = f(n-1)+f(n-2).従って,再帰と反復処理を用いることができ,再帰中の多くの繰返し計算は効率が遅すぎる.反復,時間複雑度O(n),空間複雑度O(1)を用いた.
class Solution{
public:
	static int climb(int n)
	{
		int pre = 0;
		int cur = 1;
		for(int i = 1;i <=n;++i)
		{
			int tmp = cur;
			cur+=pre;
			pre=tmp;
		}
		return cur;
	}
};