曾經(jīng)的我以為動態(tài)規(guī)劃很神秘,很難理解。后來隨著刷的動態(tài)規(guī)劃相關(guān)的題越來越多,對于動態(tài)規(guī)劃也就駕輕就熟了。我一開始來認識動態(tài)規(guī)劃是通過概念來理解的,這對于我來說總是顯得晦澀。我不是一個善于死記理論的人,反而是通過多刷題,回頭再去看動態(tài)規(guī)劃的使用情況則是有一種恍然大悟感。這樣的獲得想必也不會輕易忘記。刷題并不能讓人變得聰明,但確實能夠鍛煉一個人的思維。
遞歸 + 數(shù)組 = 動態(tài)規(guī)劃
先看一眼概念也未必是壞事:動態(tài)規(guī)劃 - 維基百科,自由的百科全書
動態(tài)規(guī)劃的所有題目,在不考慮性能的情況下,都可以使用簡單的遞歸來解決。
題目
下面來看一道 LeetCode 經(jīng)典動態(tài)規(guī)劃題目:(70) Climbing Stairs - LeetCode
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
遞歸
公式如下(這個也是做動態(tài)規(guī)劃必須要列出的公式)
我們來試試用簡單的遞歸來解決這個問題:
/**
* Created by jacob on 2019-08-20.
*/
public class Solution {
public int climbStairs(int n) {
if (n <= 2) { // 遞歸終結(jié)點
return n;
}
return climbStairs(n - 1) + climbStairs(n - 2);
}
}
如果我們這時候計算的是 climbStairs(5)
,通過下圖可以看到我們一共計算 f(3)
2次、 f(2)
3次、 f(1)
2次。這是在臺階數(shù) n 很小的情況下,如果 n 很大的話,重復(fù)計算的模塊會變的更多。
數(shù)組記錄中間結(jié)果
這個時候如果我們能夠通過一個數(shù)組來記錄中間結(jié)果就好了,當上圖中的每一個節(jié)點如果已經(jīng)計算過,就不再重復(fù)計算了。
代碼如下:
class Solution {
public int climbStairs(int n) {
int[] dp = new int[n + 1];
return this.climbStairs(dp, n);
}
private int climbStairs(int[] dp, int n) {
if (n <= 1) {
return 1;
}
if (dp[n] > 0) {
return dp[n];
}
int num = climbStairs(dp, n - 1) + climbStairs(dp, n - 2);
dp[n] = num;
return num;
}
}
去掉遞歸
遞歸會新建很多局部變量,建立很多棧幀,帶來很多不必要的消耗,如果能夠去除遞歸效率會有進一步的提升。
上面我們都是從圖中的根結(jié)點一步一步向下計算,是一個深度優(yōu)先搜索的過程,如果我們從根節(jié)點向上算就能去掉遞歸了。
代碼如下:
/**
* Created by jacob on 2019-08-20.
*/
public class Solution2 {
public int climbStairs(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (i <= 2) {
dp[i] = i;
} else {
dp[i] = dp[i - 1] + dp[i - 2];
}
}
return dp[n];
}
}
動態(tài)規(guī)劃題目
多刷點題,就啥都明白了。