当前位置:   article > 正文

斐波那契数列之动态规划_斐波那契动态规划

斐波那契动态规划

有这样一道OJ

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?

https://oj.leetcode.com/problems/climbing-stairs/

咋一看不就是简单的斐波那契数列吗,递归就行了。

但是递归的话超时了。

于是用了动态规划

  1. public class Solution {
  2. public int climbStairs(int n) {
  3. if(n==1) return 1;
  4. if(n==2) return 2;
  5. int pre = 1;
  6. int last = 2;
  7. for(int i=3; i<n; i++){
  8. int tmp = last;
  9. last += pre;
  10. pre = tmp;
  11. }
  12. return last + pre;
  13. }
  14. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/573409
推荐阅读
相关标签
  

闽ICP备14008679号