# 卿è§å ## èæ¯ å ä»ä¸éé¢ç®å¼å§~ å¦é¢  [triangle](https://leetcode-cn.com/problems/triangle/) > ç»å®ä¸ä¸ªä¸è§å½¢ï¼æ¾åºèªé¡¶åä¸çæå°è·¯å¾åãæ¯ä¸æ¥åªè½ç§»å¨å°ä¸ä¸è¡ä¸ç¸é»çç»ç¹ä¸ã ä¾å¦ï¼ç»å®ä¸è§å½¢ï¼ ```text [ [2], [3,4], [6,5,7], [4,1,8,3] ] ``` èªé¡¶åä¸çæå°è·¯å¾å为  11ï¼å³ï¼2 + 3 + 5 + 1 = 11ï¼ã ä½¿ç¨ DFSï¼éå æè åæ²»æ³ï¼ éå  åæ²»æ³  ä¼å DFSï¼ç¼åå·²ç»è¢«è®¡ç®çå¼ï¼ç§°ä¸ºï¼è®°å¿åæç´¢ æ¬è´¨ä¸ï¼å¨æè§åï¼  卿è§åå°±æ¯æå¤§é®é¢åæå°é®é¢ï¼å¹¶è§£å³äºå°é®é¢éå¤è®¡ç®çæ¹æ³ç§°ä¸ºå¨æè§å 卿è§åå DFS åºå« - äºåæ åé®é¢æ¯æ²¡æäº¤éï¼æä»¥å¤§é¨åäºåæ é½ç¨é彿è åæ²»æ³ï¼å³ DFSï¼å°±å¯ä»¥è§£å³ - å triangle è¿ç§æ¯æéå¤èµ°çæ åµï¼**åé®é¢æ¯æäº¤é**ï¼æä»¥å¯ä»¥ç¨å¨æè§åæ¥è§£å³ 卿è§åï¼èªåºåä¸ ```Python class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if len(triangle) == 0: return 0 dp = triangle[-1].copy() for i in range(-2, -len(triangle) - 1, -1): for j in range(len(triangle[i])): dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]) return dp[0] ``` 卿è§åï¼èªé¡¶åä¸ ```Python class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if len(triangle) == 0: return 0 dp = triangle[0] for row in triangle[1:]: dp_new = [row[0] + dp[0]] for i in range(len(dp) - 1): dp_new.append(row[i+1] + min(dp[i], dp[i+1])) dp_new.append(row[-1] + dp[-1]) dp = dp_new return min(dp) ``` ```Python class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: result = triangle count = 0 for line in result: line[0] += count count = line[0] for i in range(1, len(triangle)): for j in range(1, len(triangle[i])): if j >= len(triangle[i-1]): result[i][j] += result[i-1][j-1] else: result[i][j] += min(result[i-1][j-1], result[i-1][j]) return min(result[-1]) ``` ## éå½åå¨è§å ³ç³» é彿¯ä¸ç§ç¨åºçå®ç°æ¹å¼ï¼å½æ°çèªæè°ç¨ ```go Function(x) { ... Funciton(x-1); ... } ``` 卿è§åï¼æ¯ä¸ç§è§£å³é®é¢çææ³ï¼å¤§è§æ¨¡é®é¢çç»æï¼æ¯ç±å°è§æ¨¡é®é¢çç»æè¿ç®å¾æ¥çã卿è§åå¯ç¨é彿¥å®ç°(Memorization Search) ## 使ç¨åºæ¯ 满足两个æ¡ä»¶ - æ»¡è¶³ä»¥ä¸æ¡ä»¶ä¹ä¸ - æ±æå¤§/æå°å¼ï¼Maximum/Minimum ï¼ - æ±æ¯å¦å¯è¡ï¼Yes/No ï¼ - æ±å¯è¡ä¸ªæ°ï¼Count(\*) ï¼ - 满足ä¸è½æåºæè 交æ¢ï¼Can not sort / swap ï¼ å¦é¢ï¼[longest-consecutive-sequence](https://leetcode-cn.com/problems/longest-consecutive-sequence/) ä½ç½®å¯ä»¥äº¤æ¢ï¼æä»¥ä¸ç¨å¨æè§å ## åç¹è¦ç´ 1. **ç¶æ State** - çµæï¼åé åï¼åå¨å°è§æ¨¡é®é¢çç»æ 2. æ¹ç¨ Function - ç¶æä¹é´çèç³»ï¼æä¹éè¿å°çç¶æï¼æ¥ç®å¤§çç¶æ 3. åå§å Intialization - ææéçå°ç¶ææ¯ä»ä¹, èµ·ç¹ 4. çæ¡ Answer - æå¤§çé£ä¸ªç¶ææ¯ä»ä¹ï¼ç»ç¹ ## 常è§åç§ç±»å 1. Matrix DP (10%) 1. Sequence (40%) 1. Two Sequences DP (40%) 1. Backpack (10%) > 注æç¹ > > - è´ªå¿ç®æ³å¤§å¤é¢ç®é èçæ¡ï¼æä»¥å¦æè½ç¨å¨æè§å就尽éç¨å¨è§ï¼ä¸ç¨è´ªå¿ç®æ³ ## 1ãç©éµç±»åï¼10%ï¼ ### [minimum-path-sum](https://leetcode-cn.com/problems/minimum-path-sum/) > ç»å®ä¸ä¸ªå å«éè´æ´æ°ç  *m* x *n*Â ç½æ ¼ï¼è¯·æ¾åºä¸æ¡ä»å·¦ä¸è§å°å³ä¸è§çè·¯å¾ï¼ä½¿å¾è·¯å¾ä¸çæ°åæ»å为æå°ã æè·¯ï¼å¨æè§å 1. state: f(x, y) ä»èµ·ç¹èµ°å° (x, y) çæçè·¯å¾ 2. function: f(x, y) = min(f(x - 1, y), f(x, y - 1]) + A(x, y) 3. intialize: f(0, 0) = A(0, 0)ãf(i, 0) = sum(0,0 -> i,0)ã f(0, i) = sum(0,0 -> 0,i) 4. answer: f(n - 1, m - 1) 5. 2D DP -> 1D DP ```Python class Solution: def minPathSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [0] * n dp[0] = grid[0][0] for i in range(1, n): dp[i] = dp[i-1] + grid[0][i] for i in range(1, m): dp[0] += grid[i][0] for j in range(1, n): dp[j] = grid[i][j] + min(dp[j-1], dp[j]) return dp[-1] ``` ```Python class Solution: def minPathSum(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) result = grid for i in range(1, m): result[i][0] += result[i-1][0] for j in range(1, n): result[0][j] += result[0][j-1] for i in range(1, m): for j in range(1, n): result[i][j] += min(result[i-1][j], result[i][j-1]) return result[-1][-1] ``` ### [unique-paths](https://leetcode-cn.com/problems/unique-paths/) > ä¸ä¸ªæºå¨äººä½äºä¸ä¸ª m x n ç½æ ¼çå·¦ä¸è§ ï¼èµ·å§ç¹å¨ä¸å¾ä¸æ 记为âStartâ ï¼ã > æºå¨äººæ¯æ¬¡åªè½å䏿è åå³ç§»å¨ä¸æ¥ãæºå¨äººè¯å¾è¾¾å°ç½æ ¼çå³ä¸è§ï¼å¨ä¸å¾ä¸æ 记为âFinishâï¼ã > 鮿»å ±æå¤å°æ¡ä¸åçè·¯å¾ï¼ ```Python class Solution: def uniquePaths(self, m: int, n: int) -> int: if m < n: m, n = n, m dp = [1] * n for i in range(1, m): for j in range(1, n): dp[j] += dp[j - 1] return dp[-1] ``` ```Python class Solution: def uniquePaths(self, m: int, n: int) -> int: result = [[1] * n for _ in range(m)] for i in range(1, m): for j in range(1, n): result[i][j] = result[i-1][j] + result[i][j-1] return result[-1][-1] ``` ### [unique-paths-ii](https://leetcode-cn.com/problems/unique-paths-ii/) > ä¸ä¸ªæºå¨äººä½äºä¸ä¸ª m x n ç½æ ¼çå·¦ä¸è§ ï¼èµ·å§ç¹å¨ä¸å¾ä¸æ 记为âStartâ ï¼ã > æºå¨äººæ¯æ¬¡åªè½å䏿è åå³ç§»å¨ä¸æ¥ãæºå¨äººè¯å¾è¾¾å°ç½æ ¼çå³ä¸è§ï¼å¨ä¸å¾ä¸æ 记为âFinishâï¼ã > 鮿»å ±æå¤å°æ¡ä¸åçè·¯å¾ï¼ > ç°å¨èèç½æ ¼ä¸æéç¢ç©ãé£ä¹ä»å·¦ä¸è§å°å³ä¸è§å°ä¼æå¤å°æ¡ä¸åçè·¯å¾ï¼ ```Python class Solution: def uniquePathsWithObstacles(self, G: List[List[int]]) -> int: m, n = len(G), len(G[0]) dp = [1] if G[0][0] == 0 else [0] for i in range(1, n): new = dp[i-1] if G[0][i] == 0 else 0 dp.append(new) for i in range(1, m): dp[0] = 0 if G[i][0] == 1 else dp[0] for j in range(1, n): dp[j] = dp[j-1] + dp[j] if G[i][j] == 0 else 0 return dp[-1] ``` ```Python class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: if obstacleGrid[0][0]: return 0 m = len(obstacleGrid) n = len(obstacleGrid[0]) result = [[0] * n for _ in range(m)] result[0][0] = 1 for i in range(1, m): if not obstacleGrid[i][0]: result[i][0] = result[i-1][0] for j in range(1, n): if not obstacleGrid[0][j]: result[0][j] = result[0][j-1] for i in range(1, m): for j in range(1, n): if obstacleGrid[i][j]: result[i][j] = 0 else: result[i][j] = result[i-1][j] + result[i][j-1] return result[-1][-1] ``` ## 2ãåºåç±»åï¼40%ï¼ ### [climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs/) > åè®¾ä½ æ£å¨ç¬æ¥¼æ¢¯ãéè¦ Â *n* é¶ä½ æè½å°è¾¾æ¥¼é¡¶ã ```Python class Solution: def climbStairs(self, n: int) -> int: if n < 2: return n step1, step2 = 2, 1 for _ in range(n - 2): step1, step2 = step1 + step2, step1 return step1 ``` ```Python class Solution: def climbStairs(self, n: int) -> int: if n == 1: return n result = [1] * n result[1] = 2 for i in range(2, n): result[i] = result[i-1] + result[i-2] return result[-1] ``` ### [jump-game](https://leetcode-cn.com/problems/jump-game/) > ç»å®ä¸ä¸ªéè´æ´æ°æ°ç»ï¼ä½ æåä½äºæ°ç»ç第ä¸ä¸ªä½ç½®ã > æ°ç»ä¸çæ¯ä¸ªå ç´ ä»£è¡¨ä½ å¨è¯¥ä½ç½®å¯ä»¥è·³è·çæå¤§é¿åº¦ã > å¤æä½ æ¯å¦è½å¤å°è¾¾æåä¸ä¸ªä½ç½®ã è§£æ³ï¼ç´æ¥DPæ æ³å¾å°O(n)çè§£ï¼èèé´æ¥DP - tail to head ```Python class Solution: def canJump(self, nums: List[int]) -> bool: left = len(nums) - 1 # most left index that can reach the last index for i in range(len(nums) - 2, -1, -1): left = i if i + nums[i] >= left else left # DP return left == 0 ``` - head to tail ```Python class Solution: def canJump(self, nums: List[int]) -> bool: max_pos = nums[0] # furthest index can reach for i in range(1, len(nums)): if max_pos < i: return False max_pos = max(max_pos, i + nums[i]) # DP return True ``` ```Python class Solution: def canJump(self, nums: List[int]) -> bool: max_jump = 0 length = len(nums) for i in range(length): if max_jump >= i: max_jump = max(max_jump, i + nums[i]) if max_jump >= length - 1: return True return False ``` ### [jump-game-ii](https://leetcode-cn.com/problems/jump-game-ii/) > ç»å®ä¸ä¸ªéè´æ´æ°æ°ç»ï¼ä½ æåä½äºæ°ç»ç第ä¸ä¸ªä½ç½®ã > æ°ç»ä¸çæ¯ä¸ªå ç´ ä»£è¡¨ä½ å¨è¯¥ä½ç½®å¯ä»¥è·³è·çæå¤§é¿åº¦ã > ä½ çç®æ æ¯ä½¿ç¨æå°çè·³è·æ¬¡æ°å°è¾¾æ°ç»çæåä¸ä¸ªä½ç½®ã ```Python class Solution: def jump(self, nums: List[int]) -> int: cur_max = 0 step_max = 0 step = 0 for i in range(len(nums)): if cur_max < i: # can't reach i, don't have to consider in this problem return float('inf') if step_max < i: # can't reach i in current number of steps step += 1 step_max = cur_max cur_max = max(cur_max, i + nums[i]) # DP return min_step ``` ```Python class Solution: def jump(self, nums: List[int]) -> int: max_jump, step, end = 0, 0, 0 for i in range(len(nums)-1): max_jump = max(max_jump, i+nums[i]) if i == end: step += 1 end = max_jump return step ``` ### [palindrome-partitioning-ii](https://leetcode-cn.com/problems/palindrome-partitioning-ii/) > ç»å®ä¸ä¸ªå符串 _s_ï¼å° _s_ å岿ä¸äºå串ï¼ä½¿æ¯ä¸ªå䏲齿¯åæä¸²ã > è¿å符åè¦æ±çæå°å岿¬¡æ°ã - Why is hard ä» ç®æ DP, 夿忿¶é´å¤æåº¦é« -> ç®æ DP + åæäºç»´DP, åæDP空é´å¤æåº¦é« -> ä¸ç¹trick, åæDP空é´å¤æåº¦éä¸ºçº¿æ§ ```Python class Solution: def minCut(self, s: str) -> int: dp_min = [0] * len(s) dp_pal = [True] * len(s) def isPal(i, j): dp_pal[i] = (s[i] == s[j] and dp_pal[i+1]) return dp_pal[i] for j in range(1, len(s)): min_cut = dp_min[j - 1] + 1 if isPal(0, j): min_cut = 0 for i in range(1, j): if isPal(i, j): min_cut = min(min_cut, dp_min[i - 1] + 1) dp_min[j] = min_cut return dp_min[-1] ``` ```Python class Solution: def minCut(self, s: str) -> int: n = len(s) if n < 2: return 0 result = [n] * n result[0] = 0 for i in range(1, n): if s[:i+1] == s[:i+1][::-1]: result[i] = 0 continue for j in range(i): if s[j+1:i+1] == s[j+1:i+1][::-1]: result[i] = min(result[i], result[j]+1) return result[-1] ``` ### [longest-increasing-subsequence](https://leetcode-cn.com/problems/longest-increasing-subsequence/) > ç»å®ä¸ä¸ªæ åºçæ´æ°æ°ç»ï¼æ¾å°å ¶ä¸æé¿ä¸åååºåçé¿åº¦ã ååºå æ¯ç±æ°ç»æ´¾çèæ¥çåºåï¼å é¤ï¼æä¸å é¤ï¼æ°ç»ä¸çå ç´ è䏿¹åå ¶ä½å ç´ ç顺åºãä¾å¦ï¼[3,6,2,7] æ¯æ°ç» [0,3,1,6,2,2,7] çååºåã ç¤ºä¾ 1ï¼ è¾å ¥ï¼nums = [10,9,2,5,3,7,101,18] è¾åºï¼4 è§£éï¼æé¿éå¢ååºåæ¯ [2,3,7,101]ï¼å æ¤é¿åº¦ä¸º 4 ç¤ºä¾ 2ï¼ è¾å ¥ï¼nums = [0,1,0,3,2,3] è¾åºï¼4 ç¤ºä¾ 3ï¼ è¾å ¥ï¼nums = [7,7,7,7,7,7,7] è¾åºï¼1 - DP(i) çäºä»¥ç¬¬i个æ°ç»å°¾çæé¿ä¸åååºåçé¿åº¦ï¼å®¹ææ³ä½ä¸æ¯æä¼ ```Python class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if len(nums) == 0: return 0 dp_max = [1] * len(nums) for j in range(1, len(nums)): for i in range(j): if nums[j] > nums[i]: dp_max[j] = max(dp_max[j], dp_max[i] + 1) return max(dp_max) ``` - æä¼ç®æ³ä½¿ç¨ greedy + binary searchï¼æ¯è¾tricky ```Python class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if len(nums) == 0: return 0 seq = [nums[0]] for i in range(1, len(nums)): ins = bisect.bisect_left(seq, nums[i]) if ins == len(seq): seq.append(nums[i]) else: seq[ins] = nums[i] return len(seq) ``` ```Python class Solution: def lengthOfLIS(self, nums: List[int]) -> int: result = [nums[0]] length = len(nums) for i in range(1, length): if nums[i] > result[-1]: result.append(nums[i]) continue if nums[i] < result[-1]: for j in range(len(result)): if nums[i] <= result[j]: result[j] = nums[i] break return len(result) ``` ### [word-break](https://leetcode-cn.com/problems/word-break/) > ç»å®ä¸ä¸ª**é空**å符串  *s* åä¸ä¸ªå å«**é空**åè¯å表çåå ¸  *wordDict*ï¼å¤å®  *s* æ¯å¦å¯ä»¥è¢«ç©ºæ ¼æå为ä¸ä¸ªæå¤ä¸ªå¨åå ¸ä¸åºç°çåè¯ã ```Python class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dp = [False] * (len(s) + 1) dp[-1] = True for j in range(len(s)): for i in range(j+1): if dp[i - 1] and s[i:j+1] in wordDict: dp[j] = True break return dp[len(s) - 1] ``` ```Python class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: length = len(s) result = [False] * length for i in range(length): if s[:i+1] in wordDict: result[i] = True continue for j in range(i+1): if result[j] and s[j+1:i+1] in wordDict: result[i] = True break return result[-1] ``` å°ç» 常è§å¤çæ¹å¼æ¯ç» 0 ä½ç½®å ä½ï¼è¿æ ·å¤çé®é¢æ¶ä¸è§åä»ï¼åå§ååå¨åæ¥åºç¡ä¸ length+1ï¼è¿åç»æ f[n] - ç¶æå¯ä»¥ä¸ºå i 个 - åå§å length+1 - åå¼ index=i-1 - è¿åå¼ï¼f[n]æè f[m][n] ## Two Sequences DPï¼40%ï¼ ### [longest-common-subsequence](https://leetcode-cn.com/problems/longest-common-subsequence/) > ç»å®ä¸¤ä¸ªå符串  text1 å  text2ï¼è¿åè¿ä¸¤ä¸ªå符串çæé¿å ¬å ±ååºåã > ä¸ä¸ªå符串ç  ååºå Â æ¯æè¿æ ·ä¸ä¸ªæ°çå符串ï¼å®æ¯ç±åå符串å¨ä¸æ¹åå符çç¸å¯¹é¡ºåºçæ åµä¸å 餿äºå符ï¼ä¹å¯ä»¥ä¸å é¤ä»»ä½å符ï¼åç»æçæ°å符串ã > ä¾å¦ï¼"ace" æ¯ "abcde" çååºåï¼ä½ "aec" 䏿¯ "abcde" çååºåã两个å符串çãå ¬å ±ååºåãæ¯è¿ä¸¤ä¸ªå符串æå ±åæ¥æçååºåã - äºç»´DPè¥åªä¸å½åè¡åä¸ä¸è¡æå ³ï¼å¯å°ç©ºé´å¤æåº¦éå°çº¿æ§ ```Python class Solution: def longestCommonSubsequence(self, t1: str, t2: str) -> int: if t1 == '' or t2 == '': return 0 if len(t1) < len(t2): t1, t2 = t2, t1 dp = [int(t2[0] == t1[0])] * len(t2) # previous row dp_new = [0] * len(t2) # current row for j in range(1, len(t2)): dp[j] = 1 if t2[j] == t1[0] else dp[j - 1] for i in range(1, len(t1)): dp_new[0] = 1 if dp[0] == 1 or t2[0] == t1[i] else 0 for j in range(1, len(t2)): if t2[j] != t1[i]: dp_new[j] = max(dp[j], dp_new[j - 1]) else: dp_new[j] = dp[j - 1] + 1 dp, dp_new = dp_new, dp return dp[-1] ``` ```Python class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1) + 1 n = len(text2) + 1 result = [[0]*n for _ in range(m)] for i in range(1, m): for j in range(1, n): if text1[i-1] == text2[j-1]: result[i][j] = result[i-1][j-1] + 1 else: result[i][j] = max(result[i-1][j], result[i][j-1]) return result[-1][-1] ``` ### [edit-distance](https://leetcode-cn.com/problems/edit-distance/) > ç»ä½ 两个åè¯ Â word1 å  word2ï¼è¯·ä½ 计ç®åºå°  word1Â è½¬æ¢æ  word2 æä½¿ç¨çæå°æä½æ°  > ä½ å¯ä»¥å¯¹ä¸ä¸ªåè¯è¿è¡å¦ä¸ä¸ç§æä½ï¼ > æå ¥ä¸ä¸ªå符 > å é¤ä¸ä¸ªå符 > æ¿æ¢ä¸ä¸ªå符 æè·¯ï¼åä¸é¢å¾ç±»ä¼¼ï¼ç¸çåä¸éè¦æä½ï¼å¦ååå é¤ãæå ¥ãæ¿æ¢æå°æä½æ¬¡æ°çå¼+1 ```Python class Solution: def minDistance(self, w1: str, w2: str) -> int: if w1 == '': return len(w2) if w2 == '': return len(w1) m, n = len(w1), len(w2) if m < n: w1, w2, m, n = w2, w1, n, m dp = [int(w1[0] != w2[0])] * n dp_new = [0] * n for j in range(1, n): dp[j] = dp[j - 1] + int(w2[j] != w1[0] or dp[j - 1] != j) for i in range(1, m): dp_new[0] = dp[0] + int(w2[0] != w1[i] or dp[0] != i) for j in range(1, n): dp_new[j] = min(dp[j - 1] + int(w2[j] != w1[i]), dp[j] + 1, dp_new[j - 1] + 1) dp, dp_new = dp_new, dp return dp[-1] ``` ```Python class Solution: def minDistance(self, word1: str, word2: str) -> int: m = len(word1) n = len(word2) if not m*n: return m+n m, n = m + 1, n + 1 result = [[0]*n for _ in range(m)] for i in range(m): result[i][0] = i for j in range(n): result[0][j] = j for i in range(1, m): for j in range(1, n): if word1[i-1] == word2[j-1]: result[i][j] = result[i-1][j-1] else: result[i][j] = min(result[i-1][j-1], result[i-1][j], result[i][j-1]) + 1 return result[-1][-1] ``` 说æ > å¦å¤ä¸ç§åæ³ï¼MAXLEN(a,b)-LCS(a,b) ## é¶é±åèå ï¼10%ï¼ ### [coin-change](https://leetcode-cn.com/problems/coin-change/) > ç»å®ä¸åé¢é¢çç¡¬å¸ coins åä¸ä¸ªæ»éé¢ amountãç¼åä¸ä¸ªå½æ°æ¥è®¡ç®å¯ä»¥åææ»é颿éçæå°ç硬å¸ä¸ªæ°ãå¦ææ²¡æä»»ä½ä¸ç§ç¡¬å¸ç»åè½ç»ææ»éé¢ï¼è¿å  -1ã æè·¯ï¼åå ¶ä» DP ä¸å¤ªä¸æ ·ï¼i è¡¨ç¤ºé±æè 容é ```Python class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [0] * (amount + 1) for i in range(1, len(dp)): dp[i] = float('inf') for coin in coins: if i >= coin and dp[i - coin] + 1 < dp[i]: dp[i] = dp[i - coin] + 1 return -1 if dp[amount] == float('inf') else dp[amount] ``` ```Python class Solution: def coinChange(self, coins: List[int], amount: int) -> int: result = [float("inf")] * (amount+1) result[0] = 0 for i in range(1, amount+1): for j in range(len(coins)): if i >= coins[j]: result[i] = min(result[i], result[i-coins[j]]+1) if result[-1] == float("inf"): return -1 return result[-1] ``` ### [backpack](https://www.lintcode.com/problem/backpack/description) > å¨ n 个ç©å䏿éè¥å¹²ç©åè£ å ¥èå ï¼æå¤è½è£ 夿»¡ï¼å设èå ç大å°ä¸º mï¼æ¯ä¸ªç©åç大å°ä¸º A[i] ```Python class Solution: def backPack(self, m, A): n = len(A) dp = [0] * (m + 1) dp_new = [0] * (m + 1) for i in range(n): for j in range(1, m + 1): use_Ai = 0 if j - A[i] < 0 else dp[j - A[i]] + A[i] dp_new[j] = max(dp[j], use_Ai) dp, dp_new = dp_new, dp return dp[-1] ``` ```Python def backPack(weight, value, bagweight): # äºç»´æ°ç» dp = [[0] * (bagweight + 1) for _ in range(len(weight))] # åå§å for j in range(weight[0], bagweight + 1): dp[0][j] = value[0] # weightæ°ç»ç大å°å°±æ¯ç©åä¸ªæ° for i in range(1, len(weight)): # éåç©å for j in range(bagweight + 1): # éåèå 容é if j < weight[i]: dp[i][j] = dp[i - 1][j] else: dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]) return dp[len(weight) - 1][bagweight] if __name__ == "__main__": weight = [1, 3, 4] value = [15, 20, 30] bagweight = 4 result = backPack(weight, value, bagweight) print(result) ``` ### [backpack-ii](https://www.lintcode.com/problem/backpack-ii/description) > æ `n` 个ç©ååä¸ä¸ªå¤§å°ä¸º `m` çèå . ç»å®æ°ç» `A` 表示æ¯ä¸ªç©åç大å°åæ°ç» `V` 表示æ¯ä¸ªç©åçä»·å¼. > 鮿å¤è½è£ å ¥èå çæ»ä»·å¼æ¯å¤å¤§? æè·¯ï¼dp(i, j) 为å i 个ç©åï¼è£ å ¥ j èå çæå¤§ä»·å¼ ```Python class Solution: def backPackII(self, m, A, V): n = len(A) dp = [0] * (m + 1) dp_new = [0] * (m + 1) for i in range(n): for j in range(1, m + 1): use_Ai = 0 if j - A[i] < 0 else dp[j - A[i]] + V[i] # previous problem is a special case of this problem that V(i) = A(i) dp_new[j] = max(dp[j], use_Ai) dp, dp_new = dp_new, dp return dp[-1] ``` ```Python ``` ## è¡¥å ### [maximum-product-subarray](https://leetcode-cn.com/problems/maximum-product-subarray/) > æå¤§ä¹ç§¯å串 å¤çè´æ°æ åµç¨å¾®æç¹å¤æï¼æ³¨æéè¦åæ¶ DP æ£æ°ä¹ç§¯åè´æ°ä¹ç§¯ ```Python class Solution: def maxProduct(self, nums: List[int]) -> int: max_product = float('-inf') dp_pos, dp_neg = 0, 0 for num in nums: if num > 0: dp_pos, dp_neg = max(num, num * dp_pos), dp_neg * num else: dp_pos, dp_neg = dp_neg * num, min(num, dp_pos * num) if dp_pos != 0: max_product = max(max_product, dp_pos) elif dp_neg != 0: max_product = max(max_product, dp_neg) else: max_product = max(max_product, 0) return max_product ``` ```Python ``` ### [decode-ways](https://leetcode-cn.com/problems/decode-ways/) > 1 å° 26 åå«å¯¹åº a å° zï¼ç»å®è¾å ¥æ°å串ï¼é®æ»å ±æå¤å°ç§è¯ç æ¹æ³ å¸¸è§ DP é¢ï¼æ³¨æå¤çedge caseå³å¯ ```Python class Solution: def numDecodings(self, s: str) -> int: def valid_2(i): if i < 1: return 0 num = int(s[i-1:i+1]) return int(num > 9 and num < 27) dp_1, dp_2 = 1, 0 for i in range(len(s)): dp_1, dp_2 = dp_1 * int(s[i] != '0') + dp_2 * valid_2(i), dp_1 return dp_1 ``` ```Python ``` ### [best-time-to-buy-and-sell-stock-with-cooldown](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) > ç»å®è¡ç¥¨æ¯å¤©çä»·æ ¼ï¼æ¯å¤©å¯ä»¥ä¹°å ¥ååºï¼ä¹°å ¥åå¿ é¡»ååºæå¯ä»¥è¿è¡ä¸ä¸æ¬¡è´ä¹°ï¼ååºåä¸å¤©ä¸å¯ä»¥è´ä¹°ï¼é®å¯ä»¥è·å¾çæå¤§å©æ¶¦ ç»å ¸çç»´ç¹æ¯è¯ç ç±»é®é¢ï¼æ¾å°ç¶æç©ºé´åç¶æè½¬ç§»å ³ç³»å³å¯ ```Python class Solution: def maxProfit(self, prices: List[int]) -> int: buy, buy_then_nothing, sell, sell_then_nothing = float('-inf'), float('-inf'), float('-inf'), 0 for p in prices: buy, buy_then_nothing, sell, sell_then_nothing = sell_then_nothing - p, max(buy, buy_then_nothing), max(buy, buy_then_nothing) + p, max(sell, sell_then_nothing) return max(buy, buy_then_nothing, sell, sell_then_nothing) ``` ```Python class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) if n < 2: return 0 buy = [0] * n sell = [0] * n sell_s = [0] * n buy[0] = -prices[0] for i in range(1, n): buy[i] = max(buy[i-1], sell[i-1] - prices[i]) sell_s[i] = buy[i-1] + prices[i] sell[i] = max(sell_s[i-1], sell[i-1]) return max(sell[-1], sell_s[-1]) ``` ### [word-break-ii](https://leetcode-cn.com/problems/word-break-ii/) > ç»å®å符串åå¯éçåè¯åè¡¨ï¼æ±å符串ææçå岿¹å¼ æè·¯ï¼æ¤é¢ DP è§£æ³å®¹ææ³ä½å¹¶ä¸æ¯å¥½åæ³ï¼å 为å word-break ä¸åï¼æ¤é¢éè¦è¿åææå¯è¡åå²è䏿¯æ¾å°ä¸ç»å°±å¯ä»¥ãè¿éä½¿ç¨ ä¸ªäººæ¨è backtrack with memoizationã ```Python class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: n = len(s) result = [] mem = collections.defaultdict(list) wordDict = set(wordDict) def backtrack(first=0, route=[]): if first == n: result.append(' '.join(route)) return True if first not in mem: for next_first in range(first + 1, n + 1): if s[first:next_first] in wordDict: route.append(s[first:next_first]) if backtrack(next_first, route): mem[first].append(next_first) route.pop() if len(mem[first]) > 0: return True elif len(mem[first]) > 0: for next_first in mem[first]: route.append(s[first:next_first]) backtrack(next_first) route.pop() return True return False backtrack() return result ``` ```Python ``` ### [burst-balloons](https://leetcode-cn.com/problems/burst-balloons/) > n 个æ°çææä¸è¡ï¼æ¯ä¸ªæ°ç䏿ä¸ä¸ªåæ°ï¼æ¯æ¬¡æ³çä¸ä¸ªæ°çå¾å为该æ°çåæ°åç¸é»ä¸¤æ°çåæ°çä¹ç§¯ï¼æ±æå¤§å¾å æ¤é¢ä¸»è¦é¾ç¹æ¯æé DP çç¶æï¼è¿ç¨ä¸ºéçæ°çæ³ççé¡ºåº ```Python class Solution: def maxCoins(self, nums: List[int]) -> int: n = len(nums) nums.append(1) dp = [[0] * (n + 1) for _ in range(n + 1)] for dist in range(2, n + 2): for left in range(-1, n - dist + 1): right = left + dist max_coin = float('-inf') left_right = nums[left] * nums[right] for j in range(left + 1, right): max_coin = max(max_coin, left_right * nums[j] + dp[left][j] + dp[j][right]) dp[left][right] = max_coin nums.pop() return dp[-1][n] ``` ### [best-time-to-buy-and-sell-stock](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/) 121. ä¹°åè¡ç¥¨çæä½³æ¶æº ç»å®ä¸ä¸ªæ°ç» prices ï¼å®ç第 i 个å ç´ Â prices[i] è¡¨ç¤ºä¸æ¯ç»å®è¡ç¥¨ç¬¬ i 天çä»·æ ¼ã åªè½éæ© æä¸å¤© ä¹°å ¥è¿åªè¡ç¥¨ï¼å¹¶éæ©å¨ æªæ¥çæä¸ä¸ªä¸åçæ¥å ååºè¯¥è¡ç¥¨ã设计ä¸ä¸ªç®æ³æ¥è®¡ç®ä½ æè½è·åçæå¤§å©æ¶¦ã è¿åå¯ä»¥ä»è¿ç¬äº¤æä¸è·åçæå¤§å©æ¶¦ãå¦æä½ ä¸è½è·åä»»ä½å©æ¶¦ï¼è¿å 0 ã ```Python class Solution: def maxProfit(self, prices: List[int]) -> int: buy = float("inf") sell = 0 for day in prices: buy = min(buy, day) sell = max(sell, day - buy) return sell ``` ### [best-time-to-buy-and-sell-stock-ii](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/) 122. ä¹°åè¡ç¥¨çæä½³æ¶æº II ç»å®ä¸ä¸ªæ°ç» prices ï¼å ¶ä¸ prices[i] æ¯ä¸æ¯ç»å®è¡ç¥¨ç¬¬ i 天çä»·æ ¼ã 设计ä¸ä¸ªç®æ³æ¥è®¡ç®ä½ æè½è·åçæå¤§å©æ¶¦ãä½ å¯ä»¥å°½å¯è½å°å®ææ´å¤ç交æï¼å¤æ¬¡ä¹°å䏿¯è¡ç¥¨ï¼ã 注æï¼ä½ ä¸è½åæ¶åä¸å¤ç¬äº¤æï¼ä½ å¿ é¡»å¨å次è´ä¹°ååºå®æä¹åçè¡ç¥¨ï¼ã ```Python class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ length = len(prices) dp = [[0,0] for _ in range(length)] dp[0][0] = 0 dp[0][1] = -prices[0] for i in range(1, length): dp[i][0] = max(dp[i-1][0],dp[i-1][1] + prices[i]) dp[i][1] = max(dp[i-1][0]-prices[i],dp[i-1][1]) return max(dp[-1][0],dp[-1][1]) ``` ```Python class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 for i in range(1, len(prices)): tmp = prices[i] - prices[i - 1] if tmp > 0: profit += tmp return profit ``` ### [best-time-to-buy-and-sell-stock-iii](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/) 123. ä¹°åè¡ç¥¨çæä½³æ¶æº III ç»å®ä¸ä¸ªæ°ç»ï¼å®ç第 i 个å ç´ æ¯ä¸æ¯ç»å®çè¡ç¥¨å¨ç¬¬ i 天çä»·æ ¼ã 设计ä¸ä¸ªç®æ³æ¥è®¡ç®ä½ æè½è·åçæå¤§å©æ¶¦ãä½ æå¤å¯ä»¥å®æ ä¸¤ç¬ äº¤æã 注æï¼ä½ ä¸è½åæ¶åä¸å¤ç¬äº¤æï¼ä½ å¿ é¡»å¨å次è´ä¹°ååºå®æä¹åçè¡ç¥¨ï¼ã ```Python class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) buy1 = buy2 = -prices[0] sell1 = sell2 = 0 for i in range(1, n): buy1 = max(buy1, -prices[i]) sell1 = max(sell1, buy1 + prices[i]) buy2 = max(buy2, sell1 - prices[i]) sell2 = max(sell2, buy2 + prices[i]) return sell2 ``` ### [best-time-to-buy-and-sell-stock-iv](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/) 188. ä¹°åè¡ç¥¨çæä½³æ¶æº IV ç»å®ä¸ä¸ªæ´æ°æ°ç» prices ï¼å®ç第 i 个å ç´ prices[i] æ¯ä¸æ¯ç»å®çè¡ç¥¨å¨ç¬¬ i 天çä»·æ ¼ã 设计ä¸ä¸ªç®æ³æ¥è®¡ç®ä½ æè½è·åçæå¤§å©æ¶¦ãä½ æå¤å¯ä»¥å®æ k ç¬äº¤æã 注æï¼ä½ ä¸è½åæ¶åä¸å¤ç¬äº¤æï¼ä½ å¿ é¡»å¨å次è´ä¹°ååºå®æä¹åçè¡ç¥¨ï¼ã ```Python class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: days = len(prices) profit = 0 if days < 2: return profit if k >= days: for day in range(1, days): if prices[day] > prices[day-1]: profit += (prices[day] - prices[day-1]) return profit buy = [float("-inf")]* (k+1) sell = [0]* (k+1) for i in range(days): for j in range(1, k+1): buy[j] = max(buy[j], sell[j-1]-prices[i]) sell[j] = max(sell[j], buy[j]+prices[i]) return sell[-1] ``` ### [best-time-to-buy-and-sell-stock-with-transaction-fee](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) ç»å®ä¸ä¸ªæ´æ°æ°ç»Â pricesï¼å ¶ä¸ç¬¬Â i 个å ç´ ä»£è¡¨äºç¬¬Â i 天çè¡ç¥¨ä»·æ ¼ ï¼æ´æ°Â fee 代表äºäº¤æè¡ç¥¨çæç»è´¹ç¨ã ä½ å¯ä»¥æ 鿬¡å°å®æäº¤æï¼ä½æ¯ä½ æ¯ç¬äº¤æé½éè¦ä»æç»è´¹ãå¦æä½ å·²ç»è´ä¹°äºä¸ä¸ªè¡ç¥¨ï¼å¨ååºå®ä¹åä½ å°±ä¸è½åç»§ç»è´ä¹°è¡ç¥¨äºã è¿åè·å¾å©æ¶¦çæå¤§å¼ã 注æï¼è¿éçä¸ç¬äº¤ææä¹°å ¥ææå¹¶ååºè¡ç¥¨çæ´ä¸ªè¿ç¨ï¼æ¯ç¬äº¤æä½ åªéè¦ä¸ºæ¯ä»ä¸æ¬¡æç»è´¹ã ```Python class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: n = len(prices) dp = [[0, -prices[0]]] + [[0, 0] for _ in range(n - 1)] for i in range(1, n): dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee) dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]) return dp[n - 1][0] ``` ### [best-time-to-buy-and-sell-stock-with-cooldown](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) 309. æä½³ä¹°åè¡ç¥¨æ¶æºå«å·å»æ ç»å®ä¸ä¸ªæ´æ°æ°ç»ï¼å ¶ä¸ç¬¬ i 个å ç´ ä»£è¡¨äºç¬¬ i 天çè¡ç¥¨ä»·æ ¼ ãâ 设计ä¸ä¸ªç®æ³è®¡ç®åºæå¤§å©æ¶¦ã卿»¡è¶³ä»¥ä¸çº¦ææ¡ä»¶ä¸ï¼ä½ å¯ä»¥å°½å¯è½å°å®ææ´å¤ç交æï¼å¤æ¬¡ä¹°å䏿¯è¡ç¥¨ï¼: ä½ ä¸è½åæ¶åä¸å¤ç¬äº¤æï¼ä½ å¿ é¡»å¨å次è´ä¹°ååºå®æä¹åçè¡ç¥¨ï¼ã ååºè¡ç¥¨åï¼ä½ æ æ³å¨ç¬¬äºå¤©ä¹°å ¥è¡ç¥¨ (å³å·å»æä¸º 1 天)ã ```Python class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) if n < 2: return 0 buy = [0] * n sell = [0] * n sell_s = [0] * n buy[0] = -prices[0] for i in range(1, n): buy[i] = max(buy[i-1], sell[i-1] - prices[i]) sell_s[i] = buy[i-1] + prices[i] sell[i] = max(sell_s[i-1], sell[i-1]) return max(sell[-1], sell_s[-1]) ``` ## ç»ä¹ Matrix DP (10%) - [ ] [triangle](https://leetcode-cn.com/problems/triangle/) - [ ] [minimum-path-sum](https://leetcode-cn.com/problems/minimum-path-sum/) - [ ] [unique-paths](https://leetcode-cn.com/problems/unique-paths/) - [ ] [unique-paths-ii](https://leetcode-cn.com/problems/unique-paths-ii/) Sequence (40%) - [ ] [climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs/) - [ ] [jump-game](https://leetcode-cn.com/problems/jump-game/) - [ ] [jump-game-ii](https://leetcode-cn.com/problems/jump-game-ii/) - [ ] [palindrome-partitioning-ii](https://leetcode-cn.com/problems/palindrome-partitioning-ii/) - [ ] [longest-increasing-subsequence](https://leetcode-cn.com/problems/longest-increasing-subsequence/) - [ ] [word-break](https://leetcode-cn.com/problems/word-break/) Two Sequences DP (40%) - [ ] [longest-common-subsequence](https://leetcode-cn.com/problems/longest-common-subsequence/) - [ ] [edit-distance](https://leetcode-cn.com/problems/edit-distance/) Backpack & Coin Change (10%) - [ ] [coin-change](https://leetcode-cn.com/problems/coin-change/) - [ ] [backpack](https://www.lintcode.com/problem/backpack/description) - [ ] [backpack-ii](https://www.lintcode.com/problem/backpack-ii/description) Others - [ ] [maximum-product-subarray](https://leetcode-cn.com/problems/maximum-product-subarray/) - [ ] [decode-ways](https://leetcode-cn.com/problems/decode-ways/) - [ ] [best-time-to-buy-and-sell-stock-with-cooldown](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) - [ ] [word-break-ii](https://leetcode-cn.com/problems/word-break-ii/) - [ ] [burst-balloons](https://leetcode-cn.com/problems/burst-balloons/)