These problems need a table with two indexes. The indexes can be two cells of a grid, two prefixes of two strings, an item and an amount, or the ends of an interval. Say the same four steps as in the 1-D stage: state, base case, transition, answer. Draw the table on paper before you write the loops, because the loop order comes from the cells that each cell reads.
A robot or a path moves in a grid, only right or down. The problem asks for the number of paths or for the best cost of a path.
// TEMPLATE A: grid paths. The moves are only right or down.// STATE: dp[r][c] = the number of paths from the top-left cell to the cell// (r, c).func gridPaths(rows, cols int) int { dp := make([][]int, rows) for r := 0; r < rows; r++ { dp[r] = make([]int, cols) // each row needs its own make // BASE CASE: one path down the first column dp[r][0] = 1 } for c := 0; c < cols; c++ { dp[0][c] = 1 // BASE CASE: one path along the first row } for r := 1; r < rows; r++ { for c := 1; c < cols; c++ { // TRANSITION: from ABOVE plus from the LEFT dp[r][c] = dp[r-1][c] + dp[r][c-1] } } return dp[rows-1][cols-1] // ANSWER: the bottom-right cell}
The moves are BASE CASE for the first row and the first column, then TRANSITION from the cell above and the cell on the left. Each cell reads only the row above and its own row. So one row is sufficient, and the standard answer keeps one row. Fill the base cells before the main loops, or the index r-1 goes out of range.
Say it
“A cell is reached from above or from the left, so its count is the sum of those two cells. That is O(m times n) time, and I can keep one row for O(n) space.”
Template B: Two strings table
Signal
The input is two strings, and the problem compares them. The problem says common subsequence, edit distance, interleave, or a pattern that matches a text.
// TEMPLATE B: a table for two strings, with an extra row and an extra// column.// STATE: dp[i][j] = the answer for the first i bytes of a and the first j// bytes of b.// Here the answer is the length of the longest common subsequence.func commonLength(a, b string) int { // EXTRA ROW: row 0 is the empty prefix of a dp := make([][]int, len(a)+1) for i := range dp { // EXTRA COLUMN. BASE CASE: row 0 and column 0 stay 0 dp[i] = make([]int, len(b)+1) } for i := 1; i <= len(a); i++ { for j := 1; j <= len(b); j++ { if a[i-1] == b[j-1] { // the LAST bytes of the two prefixes // MATCH: the diagonal cell, plus one dp[i][j] = dp[i-1][j-1] + 1 } else { // NO MATCH: drop one last byte dp[i][j] = max(dp[i-1][j], dp[i][j-1]) } } } return dp[len(a)][len(b)] // ANSWER: the two full strings}
The moves are EXTRA ROW AND COLUMN, BASE CASE, then MATCH or NO MATCH. The cell dp[i][j] is the answer for the first i bytes of a and the first j bytes of b. So the bytes to compare are a[i-1] and b[j-1]. Row 0 and column 0 are the empty prefixes, and each problem gives them a different base value.
Say it
“dp i j is the answer for the first i characters of one string and the first j of the other. Each cell reads the diagonal, the cell above and the cell on the left, so it is O(n times m).”
Template C: Knapsack count on one row
Signal
The problem asks for the number of ways to reach an amount or a sum. A different order of the same items is not a new way.
// TEMPLATE C: count the ways to reach a sum, on one row.// STATE: dp[s] = the number of ways to make the sum s with the items seen// so far.// UNBOUNDED: each item can be used many times, so the inner loop goes// FORWARDS.func countUnbounded(items []int, target int) int { dp := make([]int, target+1) dp[0] = 1 // BASE CASE: one way to make 0, with no items // ITEMS in the outer loop: an order is not a new way for _, x := range items { for s := x; s <= target; s++ { dp[s] += dp[s-x] // ADD: dp[s-x] can already include x } } return dp[target] // ANSWER}// 0/1: each item is used at most one time, so the inner loop goes// BACKWARDS.func countZeroOne(items []int, target int) int { dp := make([]int, target+1) dp[0] = 1 // BASE CASE for _, x := range items { for s := target; s >= x; s-- { dp[s] += dp[s-x] // ADD: dp[s-x] is still the value without x } } return dp[target] // ANSWER}
The moves are BASE CASE dp[0] = 1, ITEMS in the outer loop, then ADD. The direction of the inner loop is the only difference between the two functions. A forward loop lets an item be used again. A backward loop uses each item one time. If the amount is in the outer loop, the code counts each order as a different way.
Say it
“dp of s is the number of ways to make s. I loop over the items first, so I count combinations and not orders. Forwards means unlimited use, backwards means each item once.”
Template D: State machine by day
Signal
Each day you are in one of a few states, for example “has a share” or “has no share”. A rule such as a cooldown or a fee limits the moves between the states.
// TEMPLATE D: a state machine by day. Buy and sell one share as many times// as you want.// STATE: hold = the best profit at the end of the day when you have a// share.// cash = the best profit at the end of the day when you have no share.func bestProfit(prices []int) int { if len(prices) == 0 { return 0 } // BASE CASE: on day 0 you buy, or you do nothing hold, cash := -prices[0], 0 for day := 1; day < len(prices); day++ { p := prices[day] newHold := max(hold, cash-p) // TRANSITION: keep the share, or BUY newCash := max(cash, hold+p) // TRANSITION: keep the cash, or SELL // UPDATE all the states together, from the old values hold, cash = newHold, newCash } return cash // ANSWER: a share that you still have gives no profit}
The moves are STATES, one TRANSITION for each state, then UPDATE. The table is dp[day][state], and one variable for each state compresses it. Calculate all the new values from the old values before you assign them. If you assign one state too early, the next line reads the value of today, not of yesterday.
Say it
“I keep the best profit for each state at the end of each day. Each state has one transition from yesterday, so it is O(n) time and O(1) space.”
Template E: Interval DP
Signal
The value of an operation depends on the neighbours, and each operation changes the neighbours. The problem says burst, merge, cut or multiply in a range.
// TEMPLATE E: interval DP. score(lo, k, hi) is the value of the LAST// operation, at k.// STATE: dp[lo][hi] = the best total for the items strictly between lo and// hi.func bestInterval(n int, score func(lo, k, hi int) int) int { if n < 2 { return 0 } dp := make([][]int, n) for i := range dp { // BASE CASE: an interval with no item inside is 0 dp[i] = make([]int, n) } for length := 2; length < n; length++ { // SHORT intervals first for lo := 0; lo+length < n; lo++ { hi := lo + length // SPLIT: k is the last operation in (lo, hi) for k := lo + 1; k < hi; k++ { total := dp[lo][k] + score(lo, k, hi) + dp[k][hi] dp[lo][hi] = max(dp[lo][hi], total) // TRANSITION } } } return dp[0][n-1] // ANSWER: the full interval}
The moves are LAST operation, SPLIT at k, then SHORT intervals first. The last operation divides the interval into two parts that do not touch each other. The first operation does not do that, because it makes two far items into neighbours. The loop on the length must be the outer loop, so the two shorter intervals are ready.
Say it
“I choose which item is handled last in the interval. That splits it into two independent intervals. There are n squared intervals and n split points, so it is O(n cubed).”
Template F: DFS with memo on a grid
Signal
The path in the grid moves in four directions, so no row order is correct for a table. Each move follows a strict rule, for example to a larger value, so a path cannot return to a cell.
// TEMPLATE F: DFS with a memo on a grid. A move goes to a strictly smaller// neighbour.// STATE: memo[r][c] = the length of the longest path that STARTS at (r, c).// 0 = not known.func longestDownhill(grid [][]int) int { rows, cols := len(grid), len(grid[0]) memo := make([][]int, rows) for r := range memo { memo[r] = make([]int, cols) } dirs := [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} // declare first, so the closure can call itself var dfs func(r, c int) int dfs = func(r, c int) int { if memo[r][c] != 0 { // CHECK THE MEMO return memo[r][c] } best := 1 // BASE CASE: the cell alone for _, d := range dirs { // EXPLORE the four neighbours nr, nc := r+d[0], c+d[1] if nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] < grid[r][c] { best = max(best, 1+dfs(nr, nc)) // TRANSITION } } memo[r][c] = best // STORE return best } best := 0 for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { best = max(best, dfs(r, c)) // ANSWER: the best start cell } } return best}
The moves are CHECK THE MEMO, EXPLORE the four neighbours, then STORE. The strict rule makes the recursion stop, and no visited set is necessary. The memo makes each cell cost one calculation, so the time is O(rows × cols). Without the memo the time is exponential.
Say it
“The longest path from a cell is one plus the best of its larger neighbours. I cache that per cell, so each cell is computed once: O(m times n) time and space.”
Mistakes in this stage
make([][]int, n) makes n rows that are nil. Make each row in a loop before you write to it.
Each row needs its own make. Two rows that share one slice change together.
With the extra row and column, the bytes are a[i-1] and b[j-1]. The index a[i] is off by one, and it panics on the last row.
A closure that calls itself needs two lines. Write var dfs func(r, c int) int first, then dfs = func(...).
Solved with comments
Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:
Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
The Go solution. Open step 3 last. Then close it and type the solution from memory.
Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.
Idea. The robot enters a cell from above or from the left. So the number of paths to a cell is the sum of the paths to those two cells.
Complexity. Time O(m * n), space O(n).
Go lesson.row[c] += row[c-1] reads the old row[c] before it writes the new value. That old value is the cell above.
Step 3: the Go solution
// uniquePaths solves LC 62. Time O(m * n), space O(n).// STATE: dp[r][c] = the number of paths from the top-left cell to// the cell// (r, c).// BASE CASE: dp[0][c] = 1 and dp[r][0] = 1. The first row and the// first// column have one path.// TRANSITION: dp[r][c] = dp[r-1][c] + dp[r][c-1]. The robot comes// from// ABOVE or from the LEFT.// ANSWER: dp[m-1][n-1].// The slice row compresses the table dp[m][n]: a cell reads only// the row// above and its own row.func uniquePaths(m int, n int) int { row := make([]int, n) for c := 0; c < n; c++ { row[c] = 1 // BASE CASE: the first row } for r := 1; r < m; r++ { // row[0] stays 1. That is the BASE CASE for the first // column. for c := 1; c < n; c++ { // Before the write, row[c] is the cell ABOVE (the row // r-1). // row[c-1] is the cell on the LEFT (already the row r). row[c] += row[c-1] // TRANSITION } } return row[n-1] // ANSWER: the last cell of the last row}
Idea. Compare the last bytes of two prefixes. If they are equal, they are in the common subsequence. If not, drop one of the two last bytes and keep the better result.
Complexity. Time O(n * m) for the two lengths, space O(n * m).
Go lesson. A 2-D table is a slice of slices. make([][]int, n+1) makes the outer slice only, so a loop must make each row.
Step 3: the Go solution
// longestCommonSubsequence solves LC 1143. Time O(n * m), space O(n// * m).// STATE: dp[i][j] = the length of the longest common subsequence of// the// first i bytes// of text1 and the first j bytes of text2.// BASE CASE: dp[0][j] = 0 and dp[i][0] = 0. An empty prefix has// nothing in// common.// TRANSITION: if text1[i-1] == text2[j-1], dp[i][j] = dp[i-1][j-1]// + 1.// If not, dp[i][j] = max(dp[i-1][j], dp[i][j-1]).// ANSWER: dp[n][m].func longestCommonSubsequence(text1 string, text2 string) int { n, m := len(text1), len(text2) // EXTRA ROW: row 0 is the empty prefix of text1 dp := make([][]int, n+1) for i := range dp { // EXTRA COLUMN. BASE CASE: make fills each row with 0 dp[i] = make([]int, m+1) } for i := 1; i <= n; i++ { for j := 1; j <= m; j++ { // The prefixes of length i and j end at text1[i-1] and // text2[j-1]. if text1[i-1] == text2[j-1] { // MATCH: the diagonal cell, plus this byte dp[i][j] = dp[i-1][j-1] + 1 } else { // NO MATCH: drop the last byte of text1, or the // last byte // of text2. dp[i][j] = max(dp[i-1][j], dp[i][j-1]) } } } return dp[n][m] // ANSWER: the two full strings}
309. Best Time to Buy and Sell Stock with Cooldown
Idea. At the end of each day you are in one of three states. You have a share, you sold today, or you rest with no share. A buy is possible only from the rest state, and that rule is the cooldown.
Complexity. Time O(n), space O(1).
Go lesson. Calculate the new states into new variables, then assign them in one tuple statement. Each transition must read the values of the day before.
Step 3: the Go solution
// maxProfit solves LC 309. Time O(n), space O(1).// STATE: the best profit at the end of day i, in each of three// states.// hold = you have a share. sold = you sold today. rest = no share,// and no// sale today.// BASE CASE: day 0. hold = -prices[0], sold = 0, rest = 0.// TRANSITION: hold = max(hold, rest - price). Keep the share, or// BUY after// a rest day.// sold = hold + price. SELL the share.// rest = max(rest, sold). Do nothing. The day after a sale is the// cooldown.// ANSWER: max(sold, rest) on the last day.// The three variables compress the table dp[day][state]: a day// reads only// the day before.func maxProfit(prices []int) int { if len(prices) == 0 { return 0 } // BASE CASE. A sale on day 0 is a buy and a sale on the same // day: // profit 0. hold, sold, rest := -prices[0], 0, 0 for day := 1; day < len(prices); day++ { p := prices[day] // TRANSITION: each right side reads the values of // yesterday. // not sold-p: no buy on the day after a sale newHold := max(hold, rest-p) newSold := hold + p newRest := max(rest, sold) // UPDATE the three states together hold, sold, rest = newHold, newSold, newRest } // ANSWER: a share that you still have gives no profit return max(sold, rest)}
Idea. Add the coins one at a time. Each coin adds, for each amount, the ways that already make the amount minus that coin.
Complexity. Time O(amount * n) for n coins, space O(amount).
Go lesson.dp[a] += dp[a-c] on one row replaces a 2-D table. The loop order decides what the row means, so the order is part of the algorithm.
Step 3: the Go solution
// change solves LC 518. Time O(amount * n) for n coins, space// O(amount).// STATE: dp[a] = the number of combinations that make the amount a// with the// coins seen so far.// BASE CASE: dp[0] = 1. One combination makes the amount 0: no// coins.// TRANSITION: for each coin c, dp[a] += dp[a-c]. The right side is// "one// more coin c".// ANSWER: dp[amount].// The row compresses the table dp[i][a] for the first i coins:// dp[i][a] =// dp[i-1][a] + dp[i][a-c].func change(amount int, coins []int) int { // amount+1 cells, so dp[amount] exists dp := make([]int, amount+1) dp[0] = 1 // BASE CASE // COINS in the outer loop. The combination 1+2 is counted one // time, not // as 1+2 and 2+1. // If the amount is in the outer loop, the code counts each // order (LC // 377). for _, c := range coins { // FORWARDS from c: dp[a-c] can already include the coin c. // So a coin can be used many times (unbounded). for a := c; a <= amount; a++ { // ADD the ways that end with one more coin c dp[a] += dp[a-c] } } return dp[amount] // ANSWER}
Idea. The numbers with a plus sign are a subset with the sum P. Algebra gives P = (sum + target) / 2, so count the subsets that add up to P.
Complexity. Time O(n * sum) for n numbers, space O(sum).
Go lesson. The % operator in Go keeps the sign of the left operand, so -3 % 2 is -1. Test the range of the target before you test the remainder.
Step 3: the Go solution
// findTargetSumWays solves LC 494. Time O(n * sum), space O(sum).// Let P be the sum of the numbers with a plus sign, and N the sum// with a// minus sign.// Then P - N = target, and P + N = sum.// Add the two equations: 2P = sum + target, so P = (sum + target) /// 2.// Now the problem is a 0/1 knapsack count: how many subsets add up// to P?// STATE: dp[s] = the number of subsets of the numbers seen so far// that add// up to s.// BASE CASE: dp[0] = 1. The empty subset adds up to 0.// TRANSITION: for each number x, dp[s] += dp[s-x], with s from// large to// small.// ANSWER: dp[P].// The row compresses the table dp[i][s] for the first i numbers.func findTargetSumWays(nums []int, target int) int { sum := 0 for _, x := range nums { sum += x } // GUARD 1: all plus signs give sum, all minus signs give -sum. // No // result is outside. if target > sum || target < -sum { return 0 } // GUARD 2: P must be an integer, so sum + target must be even. if (sum+target)%2 != 0 { return 0 } // P. It is 0 or more, because target >= -sum. subset := (sum + target) / 2 dp := make([]int, subset+1) dp[0] = 1 // BASE CASE for _, x := range nums { // ITEMS in the outer loop // BACKWARDS: dp[s-x] is still the value without x, so x is // used one // time. // If x is 0, the line doubles dp[s]: +0 and -0 are two // different // ways. for s := subset; s >= x; s-- { dp[s] += dp[s-x] // ADD the subsets that take x } } return dp[subset] // ANSWER}
Idea. If you used i bytes of s1 and j bytes of s2, you made exactly i + j bytes of s3. So the next byte of s3 must come from s1 or from s2, and two indexes describe the full state.
Complexity. Time O(n * m) for the lengths of s1 and s2, space O(n * m).
Go lesson.&& stops at the first false operand. So i > 0 && dp[i-1][j] never reads the index -1.
Step 3: the Go solution
// isInterleave solves LC 97. Time O(n * m), space O(n * m).// STATE: dp[i][j] = true if the first i bytes of s1 and the first j// bytes// of s2// can interleave to make the first i+j bytes of s3.// BASE CASE: dp[0][0] = true. Two empty prefixes make the empty// prefix.// TRANSITION: the last byte of that prefix of s3 is s3[i+j-1]. It// comes// from s1 or from s2:// dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] &&// s2[j-1]// == s3[i+j-1]).// ANSWER: dp[n][m].func isInterleave(s1 string, s2 string, s3 string) bool { n, m := len(s1), len(s2) if n+m != len(s3) { // GUARD: the lengths must agree, or s3[i+j-1] can be out of // range return false } dp := make([][]bool, n+1) // EXTRA ROW: row 0 uses no byte of s1 for i := range dp { // EXTRA COLUMN: column 0 uses no byte of s2 dp[i] = make([]bool, m+1) } dp[0][0] = true // BASE CASE // The loops start at 0, so they also fill row 0 and column 0. for i := 0; i <= n; i++ { for j := 0; j <= m; j++ { if i == 0 && j == 0 { continue // the base case is already there } last := s3[i+j-1] // the last byte of the prefix of s3 // TRANSITION: the last byte comes FROM S1 or FROM S2. fromS1 := i > 0 && dp[i-1][j] && s1[i-1] == last fromS2 := j > 0 && dp[i][j-1] && s2[j-1] == last dp[i][j] = fromS1 || fromS2 } } return dp[n][m] // ANSWER: all of s1 and all of s2}
Idea. The longest path from a cell is 1 plus the longest path from a larger neighbour. A path only goes up in value, so it cannot make a loop, and a memo can keep one answer for each cell.
Complexity. Time O(m * n), space O(m * n).
Go lesson. A closure that calls itself needs var dfs func(r, c int) int before the assignment. The closure reads matrix and memo from the function around it.
Step 3: the Go solution
// longestIncreasingPath solves LC 329. Time O(m * n), space O(m *// n).// A table with loops does not work here, because no row order fits// four// directions.// So the DFS finds the order, and the memo is the table.// STATE: memo[r][c] = the length of the longest increasing path// that STARTS// at (r, c).// BASE CASE: a cell with no larger neighbour has the length 1.// TRANSITION: memo[r][c] = 1 + max(memo of each neighbour with a// larger// value).// ANSWER: the maximum of memo[r][c] over all the cells.func longestIncreasingPath(matrix [][]int) int { rows, cols := len(matrix), len(matrix[0]) // 0 means "not known": a real length is 1 or more memo := make([][]int, rows) for r := range memo { memo[r] = make([]int, cols) } // down, up, right, left dirs := [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} // declare first, so the closure can call itself var dfs func(r, c int) int dfs = func(r, c int) int { if memo[r][c] != 0 { // CHECK THE MEMO return memo[r][c] } best := 1 // BASE CASE: the cell alone for _, d := range dirs { // EXPLORE the four neighbours nr, nc := r+d[0], c+d[1] if nr < 0 || nr >= rows || nc < 0 || nc >= cols { continue // out of the grid } // Strictly larger. This rule stops loops, so no visited // set is // necessary. if matrix[nr][nc] > matrix[r][c] { best = max(best, 1+dfs(nr, nc)) // TRANSITION } } memo[r][c] = best // STORE before the return return best } longest := 0 for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { // ANSWER: try each cell as the start longest = max(longest, dfs(r, c)) } } return longest}
Idea. Look at the last byte of a prefix of s. You can always skip it. If it is equal to the last byte of the prefix of t, you can also use it, so add the two counts.
Complexity. Time O(n * m) for the lengths of s and t, space O(n * m).
Go lesson.make fills an int row with 0. That is the correct base value for “an empty s cannot make a t that is not empty”.
Step 3: the Go solution
// numDistinct solves LC 115. Time O(n * m), space O(n * m).// STATE: dp[i][j] = the number of subsequences of the first i bytes// of s// that are equal to the first j bytes of t.// BASE CASE: dp[i][0] = 1. One subsequence is equal to the empty t:// take no// byte.// dp[0][j] = 0 for j > 0. The empty s cannot make a t that has// bytes.// TRANSITION: dp[i][j] = dp[i-1][j], and add dp[i-1][j-1] if s[i-1]// ==// t[j-1].// ANSWER: dp[n][m].func numDistinct(s string, t string) int { n, m := len(s), len(t) // EXTRA ROW: row 0 is the empty prefix of s dp := make([][]int, n+1) for i := range dp { // EXTRA COLUMN: column 0 is the empty prefix of t dp[i] = make([]int, m+1) dp[i][0] = 1 // BASE CASE: the empty t } for i := 1; i <= n; i++ { for j := 1; j <= m; j++ { // SKIP s[i-1]: make t[:j] from the shorter s dp[i][j] = dp[i-1][j] if s[i-1] == t[j-1] { // MATCH: also USE s[i-1] as the last byte of t[:j]. // A cell that is not part of the answer can // overflow. Go // does not panic: // the value wraps, and LeetCode says that the // answer fits // in 32 bits. dp[i][j] += dp[i-1][j-1] } } } return dp[n][m] // ANSWER}
Idea. Compare the last bytes of two prefixes. If they are equal, they cost nothing. If not, pay 1 for a delete, an insert or a replace, and each one goes to a smaller cell.
Complexity. Time O(n * m) for the two lengths, space O(n * m).
Go lesson. The built-in min accepts three values, so the three operations fit in one line.
Step 3: the Go solution
// minDistance solves LC 72. Time O(n * m), space O(n * m).// STATE: dp[i][j] = the fewest operations that change the first i// bytes of// word1// into the first j bytes of word2.// BASE CASE: dp[i][0] = i (delete i bytes). dp[0][j] = j (insert j// bytes).// TRANSITION: if word1[i-1] == word2[j-1], dp[i][j] = dp[i-1][j-1].// If not, dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]).// ANSWER: dp[n][m].func minDistance(word1 string, word2 string) int { n, m := len(word1), len(word2) // EXTRA ROW: row 0 is the empty prefix of word1 dp := make([][]int, n+1) for i := range dp { // EXTRA COLUMN: column 0 is the empty prefix of word2 dp[i] = make([]int, m+1) dp[i][0] = i // BASE CASE: delete all the i bytes } for j := 0; j <= m; j++ { dp[0][j] = j // BASE CASE: insert all the j bytes } for i := 1; i <= n; i++ { for j := 1; j <= m; j++ { if word1[i-1] == word2[j-1] { // MATCH: the last bytes are equal, no operation dp[i][j] = dp[i-1][j-1] continue } // NO MATCH: one operation, then a smaller problem. dp[i][j] = 1 + min( dp[i-1][j], // DELETE the last byte of word1 dp[i][j-1], // INSERT the last byte of word2 dp[i-1][j-1], // REPLACE the last byte of word1 ) } } return dp[n][m] // ANSWER}
Idea. Do not choose the first balloon to burst, because its neighbours change later. Choose the last balloon to burst in an interval: its neighbours are the two ends, and the two sides are independent.
Complexity. Time O(n³), space O(n²).
Go lesson.append(vals, nums...) adds all the items of a slice. The ... expands the slice into separate arguments.
Step 3: the Go solution
// maxCoins solves LC 312. Time O(n³), space O(n²).// Add a balloon with the value 1 at each end. Then think about the// LAST// balloon to burst// in an interval. When k bursts last in (lo, hi), all the other// balloons// between lo and hi// are gone. So the neighbours of k are lo and hi, and the two sides// do not// touch.// STATE: dp[lo][hi] = the most coins from all the balloons strictly// between// lo and hi.// BASE CASE: dp[lo][lo+1] = 0. No balloon is between two adjacent// indexes.// TRANSITION: dp[lo][hi] = max over k of dp[lo][k] +// vals[lo]*vals[k]*vals[hi] + dp[k][hi].// ANSWER: dp[0][size-1], the interval between the two added// balloons.func maxCoins(nums []int) int { // vals = 1, nums..., 1. The two added balloons never burst. vals := make([]int, 0, len(nums)+2) // length 0, capacity n+2 vals = append(vals, 1) vals = append(vals, nums...) vals = append(vals, 1) size := len(vals) dp := make([][]int, size) for i := range dp { // BASE CASE: make fills each row with 0 dp[i] = make([]int, size) } // SHORT intervals first. length is hi - lo, and 2 is the first // length // with a balloon. for length := 2; length < size; length++ { for lo := 0; lo+length < size; lo++ { hi := lo + length // SPLIT: k is the LAST balloon to burst in (lo, hi) for k := lo + 1; k < hi; k++ { // dp[lo][k] and dp[k][hi] are shorter intervals, so // they // are ready. coins := dp[lo][k] + vals[lo]*vals[k]*vals[hi] + dp[k][hi] dp[lo][hi] = max(dp[lo][hi], coins) // TRANSITION } } } return dp[0][size-1] // ANSWER}
Idea. Read the pattern from its last byte. A letter or a dot uses one byte of the text. A star with the byte before it matches zero copies, or one more copy and then stays in the pattern.
Complexity. Time O(n * m) for the lengths of s and p, space O(n * m).
Go lesson.s[i-1] and p[j-1] are bytes, and a byte compares with a character literal such as '*'. A small helper function keeps the two cases of the table easy to read.
Step 3: the Go solution
// isMatch solves LC 10. Time O(n * m), space O(n * m).// STATE: dp[i][j] = true if the first i bytes of s match the first// j bytes// of p.// BASE CASE: dp[0][0] = true. The empty pattern matches only the// empty// text.// TRANSITION: look at the last byte of the pattern prefix, p[j-1].// A letter or '.': dp[i][j] = dp[i-1][j-1], if s[i-1] matches// p[j-1].// A '*' with the byte x = p[j-2] before it has two cases:// ZERO copies of x: dp[i][j-2]. Drop "x*" from the pattern.// ONE MORE copy of x: dp[i-1][j], if s[i-1] matches x. Drop s[i-1]// and keep// "x*".// ANSWER: dp[n][m].func isMatch(s string, p string) bool { n, m := len(s), len(p) dp := make([][]bool, n+1) // EXTRA ROW: row 0 is the empty text for i := range dp { // EXTRA COLUMN: column 0 is the empty pattern dp[i] = make([]bool, m+1) } // BASE CASE. The other cells of column 0 stay false. dp[0][0] = true // i starts at 0, because the empty text can match a pattern // such as // "a*b*". for i := 0; i <= n; i++ { for j := 1; j <= m; j++ { if p[j-1] == '*' { // A valid pattern has a byte before each '*', so j // >= 2 // here. zero := dp[i][j-2] // ZERO copies: ignore "x*" // ONE MORE copy: s[i-1] is a copy of x, and "x*" // can match // more. more := i > 0 && matchByte(s[i-1], p[j-2]) && dp[i-1][j] dp[i][j] = zero || more } else { // A letter or '.': the last bytes match, and the // two // shorter prefixes match. dp[i][j] = i > 0 && matchByte(s[i-1], p[j-1]) && dp[i-1][j-1] } } } return dp[n][m] // ANSWER}// matchByte reports whether the pattern byte matches the text byte.// A '.' matches each byte.func matchByte(textByte, patternByte byte) bool { return patternByte == '.' || patternByte == textByte}