动态规划

例题

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

实例输入:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1.  1 阶 + 1 阶
2.  2 阶

递归解法

class Solution {

    private static int x = 0;

    public int climbStairs(int n) {

        up(0+2,n);
        up(0+1,n);

        return x;
    }


    public void up(int m,int n){


        if(m == n){
            x++;
            return;
        }else if(m>n){
            return;
        }else if(m<n){
            up(m+1,n);
            up(m+2,n);
        }
            
        }
}

如果使用一般的递归算法,则结果是正确的,但是当n足够大时,时间复杂度和空间复杂度就会变得很大。

动态规划

quora上有这样一个问题:

How should I explain dynamic programming to a 4-year-old?

一个42K赞的回答是这样的:

*writes down "1+1+1+1+1+1+1+1 =" on a sheet of paper*
"What's that equal to?"
*counting* "Eight!"
*writes down another "1+" on the left*
"What about that?"
*quickly* "Nine!"
"How'd you know it was nine so fast?"
"You just added one more"
"So you didn't need to recount because you remembered there were eight!Dynamic
Programming is just a fancy way to say 'remembering stuff to save time later'"

简单来说,动态规划就是把一个问题拆解成多个小问题,找出他们之间的关系,然后把小问题继续拆分,直到无法再拆分。

class Solution {

    private static int x = 0;

    public int climbStairs(int n) {
        
        int a = 0;
        int b = 0;
        int tmp = 0;

        if(n<3){
            return n;
        }else{
            a = 1;
            b = 2;
        }

        for(int i=0;i<n-2;i++){
            tmp = a+b;
            a = b;
            b = tmp;
        }

        return b;
    }


}
posted @ 2020-06-13 16:28  两小无猜  阅读(128)  评论(0编辑  收藏  举报