1. 程式人生 > >[LeetCode]70. Climbing Stairs 斐波那契數列&&動態規劃

[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?

Note: Given n will be a positive integer.

斐波那契數列 :f(n)=f(n-1) + f(n-2) ,此題由於並不需要儲存中間資料,直接利用引數a,b代替f(n-1) 和f(n-2)

public class LeetCode70 {

	/**
	 * @param args
	 */
	 public static int climbStairs(int n) {
		 int res=0;
		 int a=0,b=1;
		 for(int i=0;i<n;i++)
		 {
			 res=a+b;
			 a=b;
			 b=res;
		 }
		 return res;
	 }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.print(climbStairs(4));
	}

}