Dynamic Programming 动态规划
September 25, 2022
11648
开篇废话
时隔一年,又开始了我的算法生涯。唉,苦海无边,人生有涯啊。
这次先来看看DP,DP难在找到递归式和边界值。
流程
动态规划问题的一般形式就是求最值,求解的核心问题是穷举,然后找最值。
动态规划的一般流程就是三步:暴力的递归解法 -> 带备忘录的递归解法 -> 迭代的动态规划解法
具体来说,利用递归思维列出正确的 「状态转移方程」,判断算法问题是否具备 「最优子结构」,即能否通过子问题的最值得到原问题的最值,再判断是否需要用「备忘录」或者「DP table」来优化穷举过程,解决 「重叠子问题」。
思考步骤:明确 base case -> 明确「状态」-> 明确「选择」 -> 定义 dp 数组/函数的含义
模版
1 |
|
单串经典问题
最长递增子序列(Longest Increasing Subsequence,LIS)
模版
- 嵌套遍历
- binary search
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40## 朴素版
public int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
int index = 0;
dp[index] = nums[0];
for (int i = 1; i < nums.length; i++) {
if (dp[index] < nums[i]) {
dp[++index] = nums[i];
} else {
int l = 0, r = index;
while (l < r) {
int mid = (l + r) >> 1;
if (dp[mid] < nums[i]) {
l = mid + 1;
} else {
r = mid;
}
}
dp[l] = nums[i];
}
}
return index + 1;
}
## API版本
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
int len = 0;
for (int num : nums) {
int i = Arrays.binarySearch(dp, 0, len, num);
if (i < 0) {
i = -(i + 1);
}
dp[i] = num;
if (i == len) {
len++;
}
}
return len;
}
问题
- 300.Longest Increasing Subsequence
- 673.Number of Longest Increasing Subsequence
- 354.Russian Doll Envelopes
- 368.Largest Divisible Subset
参考
最大子数组和
模版
1 |
|
矩阵的话,方法类似:算出每一列的前缀和,然后遍历所有情况的行组合。O(n^2m)
问题
- 53.Maximum Subarray
- 152.Maximum Product Subarray
- 918.Maximum Sum Circular Subarray
- 面试题 17.24. Max Submatrix LCCI
- 363. Max Sum of Rectangle No Larger Than K
最大子数组和变体:House Robber
模版
1 |
|
问题
- 198.House Robber
- 213.House Robber II
- 337.House Robber III
- 740.Delete and Earn
- 1388. Pizza With 3n Slices
需要两个位置的情况
问题
其他
问题
- 1055.Shortest Way to Form String
- 32.Longest Valid Parentheses 两种方法,空间复杂度O(n)和O(1)
- 413. Arithmetic Slices
- 91.Decode Ways 考虑各种情况
- 132.Palindrome Partitioning II
- 583.Delete Operation for Two Strings Edit Distance
- 338.Counting Bits
- 801.Minimum Swaps To Make Sequences Increasing
- 871.Minimum Number of Refueling Stops 贪心比较容易想,但是dp的话,还是有点复杂的
带维度的单串!!
增加维度,通常用 k 表示,k 随着题目的不同,可以表示长度,个数,次数,颜色等,同时 k 这个维度的枚举和转移可能涉及到二分,贪心等算法
问题
- 256. Paint House
- 265. Paint House II
- 1473.Paint House III
- 813.Largest Sum of Averages 这题并不难,就是很烦
887.Super Egg Drop 测试题 - 975.Odd Even Jump TreeMap
- 403.Frog Jump
- 1478.Allocate Mailboxes 搞不定啊!能想到大概思路,但是实现有困难
- 1230. Toss Strange Coins 太多细节啦
买卖股票
- 121.Best Time to Buy and Sell Stock
- 122.Best Time to Buy and Sell Stock II
- 123.Best Time to Buy and Sell Stock III
- 188.Best Time to Buy and Sell Stock IV
- 309.Best Time to Buy and Sell Stock with Cooldown
- 714.Best Time to Buy and Sell Stock with Transaction Fee
双串经典问题
最长公共子序列(LCS)
- 1143.Longest Common Subsequence
- 712. Minimum ASCII Delete Sum for Two Strings
- 718.Maximum Length of Repeated Subarray
- 72.Edit Distance
- 44.Wildcard Matching
- 10.Regular Expression Matching // todo
其他
问题
矩阵问题
无串问题
前缀和
单纯实现
问题
数据结构维护前缀和
常见数据结构
- 哈希表
- 键是前缀和(状态)的值,值为第一次出现时的索引
- 键是前缀和(前缀状态)的值,值为出现次数
- 键是前缀和模 K 的余数(可以理解为前缀状态,状态为前缀和模K)
- 二维数组
- 线段树
- 其他:
- 前缀和(积)与后缀和(积)均需要
- 二维前缀和
问题
- 325. Maximum Size Subarray Sum Equals k
- 525. Contiguous Array
- 1371. Find the Longest Substring Containing Vowels in Even Counts
- 560. Subarray Sum Equals K
- 1248. Count Number of Nice Subarrays
- 523. Continuous Subarray Sum
- 974. Subarray Sums Divisible by K
- 238. Product of Array Except Self
- 724. Find Pivot Index
- 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum
- 1074. Number of Submatrices That Sum to Target
- 1314. Matrix Block Sum
- 363. Max Sum of Rectangle No Larger Than K
- 152. Maximum Product Subarray
- 713. Subarray Product Less Than K
- 1352. Product of the Last K Numbers
- 1310. XOR Queries of a Subarray
- 1442. Count Triplets That Can Form Two Arrays of Equal XOR
- 370. Range Addition
区间动态规划
回文系列
- 5.Longest Palindromic Substring // todo: classic
- 647.Palindromic Substrings
- 516.Longest Palindromic Subsequence // todo: classic
- 730.Count Different Palindromic Subsequences // todo: 地狱模式
- 1312.Minimum Insertion Steps to Make a String Palindrome
- 1147. Longest Chunked Palindrome Decomposition // todo: 地狱模式
- 1216.Valid Palindrome III
下面的我一道都不会,被自己蠢哭了【放弃。想转行了
未归类,我还没做,等慢慢做吧
- 42.Trapping Rain Water
- 818.Race Car
- 2272.Substring With Largest Variance
- 903.Valid Permutations for DI Sequence
- 22.Generate Parentheses
- 629.K Inverse Pairs Array
- 458.Poor Pigs
- 118.Pascal’s Triangle
- 1048.Longest String Chain
- 410.Split Array Largest Sum
- 823.Binary Trees With Factors
- 329.Longest Increasing Path in a Matrix
- 322.Coin Change
- 828.Count Unique Characters of All Substrings of a Given String
- 62.Unique Paths
- 1235.Maximum Profit in Job Scheduling
- 472.Concatenated Words
- 968.Binary Tree Cameras
- 1639.Number of Ways to Form a Target String Given a Dictionary
- 526.Beautiful Arrangement
- 70.Climbing Stairs
- 139.Word Break
- 509.Fibonacci Number
- 1240.Tiling a Rectangle with the Fewest Squares
- 55.Jump Game
- 1220.Count Vowels Permutation
- 473.Matchsticks to Square
- 124.Binary Tree Maximum Path Sum
- 45.Jump Game II
- 140.Word Break II
- 1696.Jump Game VI
- 1326.Minimum Number of Taps to Open to Water a Garden
- 97.Interleaving String
- 465.Optimal Account Balancing
- 2035.Partition Array Into Two Arrays to Minimize Sum Difference
- 576.Out of Boundary Paths
- 1654.Minimum Jumps to Reach Home
- 691.Stickers to Spell Word
- 131.Palindrome Partitioning
- 377.Combination Sum IV
- 907.Sum of Subarray Minimums
- 312.Burst Balloons
- 85.Maximal Rectangle
- 552.Student Attendance Record II
- 2008.Maximum Earnings From Taxi
- 787.Cheapest Flights Within K Stops
- 474.Ones and Zeroes
- 678.Valid Parenthesis String
- 1937.Maximum Number of Points with Cost
- 416.Partition Equal Subset Sum
- 1611.Minimum One Bit Operations to Make Integers Zero
- 1641.Count Sorted Vowel Strings
- 241.Different Ways to Add Parentheses
- 983.Minimum Cost For Tickets
- 741.Cherry Pickup
- 790.Domino and Tromino Tiling
- 698.Partition to K Equal Sum Subsets
- 376.Wiggle Subsequence
- 63.Unique Paths II
- 943.Find the Shortest Superstring
- 1799.Maximize Score After N Operations
- 95.Unique Binary Search Trees II
- 435.Non-overlapping Intervals
- 894.All Possible Full Binary Trees
- 1547.Minimum Cost to Cut a Stick
- 1884.Egg Drop With 2 Eggs and N Floors
- 87.Scramble String
- 1031.Maximum Sum of Two Non-Overlapping Subarrays
- 494.Target Sum
- 1277.Count Square Submatrices with All Ones
- 542.01 Matrix
- 1000.Minimum Cost to Merge Stones
- 2262.Total Appeal of A String
- 2355.Maximum Number of Books You Can Take
- 1567.Maximum Length of Subarray With Positive Product
- 486.Predict the Winner
- 1043.Partition Array for Maximum Sum
- 1335.Minimum Difficulty of a Job Schedule
- 96.Unique Binary Search Trees
- 935.Knight Dialer
- 392.Is Subsequence
- 1493.Longest Subarray of 1’s After Deleting One Element
- 518.Coin Change II
- 1770.Maximum Score from Performing Multiplication Operations
- 746.Min Cost Climbing Stairs
- 1125.Smallest Sufficient Team
- 2311.Longest Binary Subsequence Less Than or Equal to K
- 845.Longest Mountain in Array
- 834.Sum of Distances in Tree
- 1524.Number of Sub-arrays With Odd Sum
- 464.Can I Win
- 688.Knight Probability in Chessboard
- 418.Sentence Screen Fitting
- 1537.Get the Maximum Score
- 1162.As Far from Land as Possible
- 1723.Find Minimum Time to Finish All Jobs
- 847.Shortest Path Visiting All Nodes
- 1049.Last Stone Weight II
- 1387.Sort Integers by The Power Value
- 1578.Minimum Time to Make Rope Colorful
- 1025.Divisor Game
- 964.Least Operators to Express Number
- 1349.Maximum Students Taking Exam
- 2100.Find Good Days to Rob the Bank
- 2172.Maximum AND Sum of Array
- 926.Flip String to Monotone Increasing
- 1994.The Number of Good Subsets
- 361.Bomb Enemy
- 333.Largest BST Subtree
- 1617.Count Subtrees With Max Distance Between Cities
- 1359.Count All Valid Pickup and Delivery Options
- 2327.Number of People Aware of a Secret
- 2050.Parallel Courses III
- 1525.Number of Good Ways to Split a String
- 1155.Number of Dice Rolls With Target Sum
- 902.Numbers At Most N Given Digit Set
- 1531.String Compression II
- 1664.Ways to Make a Fair Array
- 2184.Number of Ways to Build Sturdy Brick Wall
- 1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance
- 1395.Count Number of Teams
- 1653.Minimum Deletions to Make String Balanced
- 1012.Numbers With Repeated Digits
- 2188.Minimum Time to Finish the Race
- 1186.Maximum Subarray Sum with One Deletion
- 1986.Minimum Number of Work Sessions to Finish the Tasks
- 568.Maximum Vacation Days
- 2338.Count the Number of Ideal Arrays
- 2291.Maximum Profit From Trading Stocks
- 920.Number of Music Playlists
- 1130.Minimum Cost Tree From Leaf Values
- 1105.Filling Bookcase Shelves
- 2222.Number of Ways to Select Buildings
- 487.Max Consecutive Ones II
- 799.Champagne Tower
- 1483.Kth Ancestor of a Tree Node
- 1014.Best Sightseeing Pair
- 1463.Cherry Pickup II
- 996.Number of Squareful Arrays
- 639.Decode Ways II
- 2060.Check if an Original String Exists Given Two Encoded Strings
- 1255.Maximum Score Words Formed by Letters
- 1449.Form Largest Integer With Digits That Add up to Target
- 1575.Count All Possible Routes
- 1977.Number of Ways to Separate Numbers
- 1402.Reducing Dishes
- 838.Push Dominoes
- 119.Pascal’s Triangle II
- 1062.Longest Repeating Substring
- 1671.Minimum Number of Removals to Make Mountain Array
- 646.Maximum Length of Pair Chain
- 689.Maximum Sum of 3 Non-Overlapping Subarrays
- 1425.Constrained Subsequence Sum
- 2266.Count Number of Texts
- 727.Minimum Window Subsequence
- 1638.Count Substrings That Differ by One Character
- 2361.Minimum Costs Using the Train Line
- 2320.Count Number of Ways to Place Houses
- 638.Shopping Offers
- 1191.K-Concatenation Maximum Sum
- 1262.Greatest Sum Divisible by Three
- 471.Encode String with Shortest Length
- 1643.Kth Smallest Instructions
- 956.Tallest Billboard
- 1626.Best Team With No Conflicts
- 1787.Make the XOR of All Segments Equal to Zero
- 2163.Minimum Difference in Sums After Removal of Elements
- 1137.N-th Tribonacci Number
- 562.Longest Line of Consecutive One in Matrix
- 600.Non-negative Integers without Consecutive Ones
- 1416.Restore The Array
- 233.Number of Digit One
- 357.Count Numbers with Unique Digits
- 1218.Longest Arithmetic Subsequence of Given Difference
- 2086.Minimum Number of Buckets Required to Collect Rainwater from Houses
- 351.Android Unlock Patterns
- 978.Longest Turbulent Subarray
- 2218.Maximum Value of K Coins From Piles
- 1931.Painting a Grid With Three Different Colors
- 1227.Airplane Seat Assignment Probability
- 1706.Where Will the Ball Fall
- 1691.Maximum Height by Stacking Cuboids
- 2370.Longest Ideal Subsequence
- 877.Stone Game