递归与动态规划关系

递归与动态规划关系

       其实递归与动态规划有紧密的关系,且一般递归都可以转化为动态规划。这个问题从一般的递归构成就能够解释清楚,
首先,问题可以分解,拆成很多重叠子问题才可以求解,而动态规划也是这一思路,说白了动态规划其实就是记忆化了的
递归程序。动态规划把很多递归问题的解存储下来,这样就省去了求许多子问题的解,从而达到了快速求解的目的。
       递归其实就是自上往下求解,常见的递归形式就是
dfs(int n){
  if(n == ?)
   return 
  dfs(n-1)
}
从顶部一直向下迭代,这点与动态规划相反,动态规划的思路常常是从底向上其常见的形式为
dp[n][n];
dp[0][0] = ?;
dp[1][0] = ?
for(int i = 1; i < n; i++){
   for(int j = i; j < n; j++){
  dp[i][j] = max(dp[i - 1][j], dp[i][j-1]) + ?
}
}
这两种形式是相反的,但是解决问题的形式是一样的,都是不断迭代到底层,递归只不过较多的堆栈存储临时数据而已。
具体问题可以看算法导论的动态规划,分钢管实例。
下面是leetcode的一些实例 70. 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?

Note: Given n will be a positive integer.
Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
动态规划做法:
class Solution {
    int res = 0;
    int[] dp;
    public int climbStairs(int n) {
        if(n == 1 || n == 0)
            return 1;
        dp = new int[n+5];
        dp[0] = 1;
        dp[1] = 1;  
        for(int i = 2; i <= n; i++){
            dp[i] = dp[i-1] + dp[i-2] ;
        }
        res = dp[n];
        return res;
        
    }
}

递归做法:
class Solution {
private:
    vector<int> memo;

    int calcWays(int n){

        if( n == 0 || n == 1)
            return 1;

        if( memo[n] == -1 )
            memo[n] = calcWays(n-1) + calcWays(n-2);

        return memo[n];
    }
public:
    int climbStairs(int n) {

        memo = vector<int>(n+1,-1);//初始化数组
        return calcWays(n);
    }
};




  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值