您的位置:首页 > 其它

递归与动态规划关系

2017-11-16 20:10 344 查看

递归与动态规划关系

       其实递归与动态规划有紧密的关系,且一般递归都可以转化为动态规划。这个问题从一般的递归构成就能够解释清楚,
首先,问题可以分解,拆成很多重叠子问题才可以求解,而动态规划也是这一思路,说白了动态规划其实就是记忆化了的
递归程序。动态规划把很多递归问题的解存储下来,这样就省去了求许多子问题的解,从而达到了快速求解的目的。
       递归其实就是自上往下求解,常见的递归形式就是
dfs(int n){
if(n == ?)
return
dfs(n-1)
}
从顶部一直向下迭代,这点与动态规划相反,动态规划的思路常常是从底向上其常见的形式为
dp

;
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
;
return res;

}
}


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

int calcWays(int n){

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

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

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

memo = vector<int>(n+1,-1);//初始化数组
return calcWays(n);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息