题目:
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?
代码:
class Solution { public: int climbStairs(int n) { int prev = 0; int curr = 1; for (int i = 0; i<n; ++i) { const int tmp = curr; curr = curr + prev; prev = tmp; } return curr; } };
Tips:
1. 这道题可以抽象成求Fibonacci数列的通项(只看最后一步:从n-1到n迈一个台阶;从n-2到n迈两个台阶)
时间: 2024-10-11 21:33:49