【Leetcode】【Easy】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?
解题:
简单的运算后,可知此题为斐波那契数列生成题。
解题步骤:
1、新建三个初始变量step1 = 1,step2 = 2,result;
2、注意算法从n = 3开始,所以当n < 3时,直接返回结果。
1 class Solution { 2 public: 3 int climbStairs(int n) { 4 int result = 0; 5 int stepOne = 1; 6 int stepTwo = 2; 7 8 if (n == 1 || n == 2) 9 return n; 10 11 while (n-- && n >= 2) { 12 result = stepOne + stepTwo; 13 stepOne = stepTwo; 14 stepTwo = result; 15 } 16 17 return result; 18 } 19 };
附录:
斐波那契以及其他有趣数学数列