Monday, April 8, 2013

Climbing Stairs (C++ code)

LeetCode Climbing StairsApr 3 '12
难度2,出现频率5
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?

思路:简单的递归,Fibonacci数列。
Tips: 用数组挨个存结果,省去了重复计算,比直接recersive function call速度要快。


 int climbStairs(int n){
  if(n == 0) return 0;
  int A[n];
  A[0] = 1; A[1] = 2;
  
  for(int i = 2; i < n; i++ ){
    A[i] = A[i-1] + A[i-2];
  }
 
  return A[n-1];
}

No comments:

Post a Comment