数据结构与算法之动态规划:二维DP(2)
一、0/1背包问题:0/1 Knapsack
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
0/*:可以有重复的
递归解法:subset w<=14 max V -->时间复杂度O(2**n)
DP解法:i:item珠宝 j:W 当前允许抢劫的重量 T(i, j) = max Value 得到的最大的value

1 # O(kn) -->k:重量 2 def knapSack(W, wt, val, n): 3 K = [[0 for x in range(W+1)] for x in range(n+1)] 4 for i in range(n+1): 5 for w in range(W+1): 6 if i == 0 or w == 0: 7 K[i][w] = 0 8 elif wt[i-1] <= w: 9 K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) 10 else: 11 K[i][w] = K[i-1][w] 12 return K[n][W]
1 def kbag(n, c, w, val): 2 dp = [[0 for i in range(c+1)] for i in range(n+1)] 3 for i in range(n+1): 4 for j in range(c+1): 5 if i == 0 or j == 0: 6 dp[i][j] = 0 7 elif w[i-1] <= j: 8 dp[i][j] = max(dp[i-1][j], dp[i-1, j-w[i-1]]+val[i-1]) 9 else: 10 dp[i][j] = dp[i-1][j] 11 12 return dp[n][c]
可以对珠宝进行切割
每一个珠宝都可能有多个
二、最大公共子序列:Longest Common Substring
Given two strings ‘X’ and ‘Y’, find the length of the longest common substring.
Input : X = "abcdxyz", y = "xyzabcd"
Output : 4
The longest common substring is "abcd" and is of length 4.
Input : X = "zxabcdezy", y = "yzabcdezx"
Output : 6
The longest common substring is "abcdez" and is of length 6.

1 def LCS(X, Y, m, n): # O(mn) 2 matrix = [[0 for k in range(n+1)] for l in range(m+1)] 3 res = 0 4 for i in range(m+1): 5 for j in range(n + 1): 6 if i == 0 or j == 0: 7 matrix[i][j] = 0 8 elif X[i-1] == Y[j-1]: 9 matrix[i][j] = matrix[i-1][j-1] + 1 10 res = max(res, matrix[i][j]) 11 else: 12 matrix[i][j] = max(matrix[i-1][j], matrix[i][j-1]) 13 return res
三、最长增长子序列:Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
1 #排序+LCS O(nlogn+n**2) 2 def lengthOfLIS1(nums): 3 sortNums = sorted(nums) 4 n = len(nums) 5 return LCS(nums, sortNums, n, n)
1 #L(i) = 1 + max(L(j)) 0<=j<i a[j]<a[i] or 1 if no such j 2 def LIS(nums): 3 dp = [1 for i in range(len(nums))] 4 for i in range(1, len(nums)): 5 for j in range(i): 6 if a[j] < a[i]: 7 dp[i] = max(dp[i], 1+dp[j]) 8 return max(dp)
1 def lengthLIS(nums): 2 temp = [] 3 for num in nums: 4 pos = bisect(temp, num) 5 if pos >= len(temp): 6 temp.append(num) 7 else: 8 temp[pos] = num 9 return len(temp)


浙公网安备 33010602011771号