word1 and word2 consist of lowercase English letters.
Solution
Approach #0
funcminDistance(word1 string, word2 string) int { m, n :=len(word1), len(word2) dp :=make([][]int, m+1)for i :=0; i < m+1; i++ { dp[i] =make([]int, n+1) dp[i][0] = i }for i :=0; i < n+1; i++ { dp[0][i] = i }for i :=1; i < m+1; i++ {for j :=1; j < n+1; j++ { a, b, c := dp[i][j-1]+1, dp[i-1][j]+1, dp[i-1][j-1]if word1[i-1] != word2[j-1] { c +=1 } dp[i][j] =min(a, min(b, c)) } }return dp[m][n]}funcmin(a, b int) int {if a < b {return a }return b}
Approach #1
funcminDistance(word1 string, word2 string) int { m, n :=len(word1), len(word2) dp :=make([]int, n+1)for i :=0; i < n+1; i++ { dp[i] = i }var ld intfor i :=1; i < m+1; i++ { ld = dp[0] dp[0] = ifor j :=1; j < n+1; j++ { a, b, c := dp[j-1]+1, dp[j]+1, ldif word1[i-1] != word2[j-1] { c +=1 } ld = dp[j] dp[j] =min(a, min(b, c)) } }return dp[n]}funcmin(a, b int) int {if a < b {return a }return b}
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
funccoinChange(coins []int, amount int) int { dp :=make([]int, amount+1)for i :=1; i < amount+1; i++ { dp[i] = amount +1 }for i :=1; i <= amount; i++ {for _, v :=range coins {if v <= i { dp[i] =min(dp[i], dp[i-v]+1) } } }if dp[amount] > amount {return-1 }return dp[amount]}funcmin(a, b int) int {if a < b {return a }return b}
funcintegerBreak(n int) int { dp :=make([]int, n+1)for i :=2; i <= n; i++ {var cur intfor j :=1; j < i; j++ { cur =max(cur, max(j*(i-j), j*dp[i-j])) } dp[i] = cur }return dp[n]}funcmax(a, b int) int {if a > b {return a }return b}
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 10^4
1 <= m * n <= 10^4
-10^5 <= mat[i][j] <= 10^5
Solution
Approach #0
funcfindDiagonalOrder(mat [][]int) []int { m, n :=len(mat), len(mat[0]) ans :=make([]int, 0, m*n)for i :=0; i < m+n-1; i++ {if i%2==1 { x :=max(i-n+1, 0) y :=min(i, n-1)for x < m && y >=0 { ans =append(ans, mat[x][y]) x++ y-- } } else { x :=min(i, m-1) y :=max(i-m+1, 0)for x >=0&& y < n { ans =append(ans, mat[x][y]) x-- y++ } } }return ans}funcmin(a, b int) int {if a < b {return a }return b}funcmax(a, b int) int {if a > b {return a }return b}