• leetcode70


    public class Solution {
        public int ClimbStairs(int n) {
            //递归方法,效率低
                //if (n <= 0)
                //{
                //    return 0;
                //}
                //else if (n == 1)
                //{
                //    return 1;
                //}
                //else if (n == 2)
                //{
                //    return 2;
                //}
                //else
                //{
                //    return ClimbStairs(n - 1) + ClimbStairs(n - 2);
                //}
    
                //非递归方法
                if (n <= 0)
                {
                    return 0;
                }
                else if (n == 1)
                {
                    return 1;
                }
                else if (n == 2)
                {
                    return 2;
                }
                else
                {
                    int[] ary = new int[n];
                    ary[0] = 1;
                    ary[1] = 2;
                    for (int i = 2; i < n; i++)
                    {
                        ary[i] = ary[i - 1] + ary[i - 2];
                    }
                    return ary[n - 1];
                }
        }
    }

    https://leetcode.com/problems/climbing-stairs/#/description

    C++版本:

    class Solution {
    public:
        int climbStairs(int n) {
            vector<int> step;
            step.push_back(1);//只有一级台阶,1种走法
            step.push_back(2);//有两级台阶,2种走法
            for (int i = 2; i <= n; i++)
            {
                //之后每一级台阶,有i-1台阶的走法+i-2台阶的走法之和
                step.push_back(step[i - 1] + step[i - 2]);
            }
            return step[n - 1];
            //4 1+1+1+1,
            //  1+1+2,1+2+1,2+1+1,
            //  2+2
    
            //5 1+1+1+1+1
            //  1+1+1+2,1+1+2+1,1+2+1+1,2+1+1+1
            //  1+2+2,2+1+2,2+2+1,
    
        }
    };

    补充一个python的实现:

     1 class Solution:
     2     def climbStairs(self, n: 'int') -> 'int':
     3         if n <= 2:
     4             return n
     5         else:
     6             dp = [0] * (n + 1)
     7             dp[1] = 1
     8             dp[2] = 2
     9             for i in range(3,n+1):
    10                 dp[i] = dp[i-1] + dp[i-2]
    11             return dp[n]

    动态规划的基本题型,斐波那契数列计算。

  • 相关阅读:
    MySQL多表查询
    多表关联
    MySQL数据类型 约束
    初识数据库
    socker server和 event
    os 模块 和 os模块下的path模块
    sys 模块
    time 模块
    目录规范

  • 原文地址:https://www.cnblogs.com/asenyang/p/6732692.html
Copyright © 2020-2023  润新知