動態規劃(Dynamic Programming)
從分治到動態規劃:動態規劃的基本思想是將待求解的問題分解為若干個子問題,這與分治的思想類似,
不同的地方在于當子問題之間是相互獨立的,這時候分治算法是我們解決問題的最好的思路,因為不同的子問題求解不會有公共的重復計算的地方,然而,當分解得到的子問題不相互獨立時,動態規劃就是我們最好的選擇,我們可以建立一個cache來記錄重復計算的部分,從而避免重復計算。后面會講到這會使得一個多項式級別的問題變為線性的時間
關鍵點:找子問題,如果一個問題具有無后效性,即后面的結果不會對前面的結果再次產生影響,可以選擇使用動態規劃。然而后面問題解的更改會倒置前面最優解發生變化,比如:下圍棋,等策略游戲的編程就無法使用動態規劃,一般采取回溯算法。
狀態轉移方程:這是動態規劃的核心,一般找出前面狀態的最優解和當前狀態最優解的關系即為狀態轉移方程。例如:最大子數組問題,我們可以找出前面以所有位置為結尾的最大子數組,隨后求出最大的作為結果;再比如:買股票,我們可以建模為:dp[i]
表示第i
天將股票賣出可以獲得的最大利潤,從而求得取所有子結果最大值作為全局最優;再比如:爬樓梯問題我們可以建模為 dp[i] = dp[i - 1] + dp[i - 2]
表示第i
次我可以選擇爬一層或者爬兩層來決定全局方案總數。
使用場景:一般的對于一個算法問題,我們首先可以暴力求解,觀察他的復雜度,如果這個復雜度是k^n復雜度,可以考慮優化為O(nk)
這時候一般會采取建立k維動態矩陣求解。
可實施性:一般的對于k^n都的復雜度算法都可以看成當前狀態和前面k個狀態有關,于是我們可以采用遞歸的方式(top down),然而這樣會導致下面的某個節點會被重復計算很多次,因為上方父節點會用到,每用到一次,下方節點就需要重新計算一次,于是我們可以采用建立緩存記錄計算過的值或者就是我們所說的動態數組(bottom up)避免重復計算,從而大大地優化了時間復雜度。舉例:斐波那契額數列通項式f(n) = f(n - 1) + f(n - 2)
如果我們采用遞歸的方式解決,會是O(2^n)
的復雜度,因為遞歸采取的是從f(n)
計算到f(1), f(2)
,回溯到f(n)
,而我們采用動態數組``dp[i] = dp[i - 1] + dp[i - 2]即從前向后則可以使得前面的值得以記錄。復雜度降為
O(n)`
一維動規優化
優化點:空間的優化,因為大多數問題我們通過動態方程可以看出,當前狀態只與前面的一個或者倆個狀態決定。如題目中所說三個問題: maxSubarray:dp[i] = max(dp[i - 1] + nums[i], nums[i])
;sell stock: dp[i] = max(dp[i - 1] + nums[i] - nums[i - 1], 0)
;Climbing Stairs: dp[i] = dp[i - 1] + dp[i - 2]
。觀察這三個動態方程我們發現當前狀態都是只與dp[i - 1]
或者 dp[i - 2]
有關。于是我們可以考慮用指針來記錄前面的兩個或一個狀態點的值,從而完成當前狀態的計算。而不需要取申請數組。下面給出三個問題的原版和優化版的解決方案:
- maxSubarray:
題目:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
常規數組解法O(n)空間:
public int maxSubArray(int[] A) {
int n = A.length;
int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
dp[0] = A[0];
int max = dp[0];
for(int i = 1; i < n; i++){
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
優化為O(1)空間:
import sys
class Solution(object):
def maxSubArray(self, nums):
res = -sys.maxint
pre = 0
for i in nums:
if pre <= 0:
pre = i
res = max(res, pre)
else:
pre = pre + i
res = max(res, pre)
return res
- 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?
常規數組解法O(n)空間:
# Bottom up, O(n) space
def climbStairs2(self, n):
if n == 1:
return 1
res = [0 for i in xrange(n)]
res[0], res[1] = 1, 2
for i in xrange(2, n):
res[i] = res[i-1] + res[i-2]
return res[-1]
優化為O(1)空間:
class Solution(object):
def climbStairs(self, n):
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
pre = 2
prepre = 1
for i in xrange(n - 2):
tmp = pre + prepre
prepre = pre
pre = tmp
return pre
- sell stock
題目:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
O(n)空間的思路可以讀者自己寫,給出O(1)的思路
import sys
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n <= 1:
return 0
res = 0
minP = prices[0]
for i in xrange(1, n):
res = max(res, prices[i] - minP)
minP = min(prices[i], minP)
return res
下期分析不能進行空間優化的一維動態規劃。有不足的地方請指正
轉載著名出處:http://www.lxweimin.com/p/62e54802d12c