动规背包总结篇
题目1:322. 零钱兑换
讲解
leetcode
class Solution {
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
var dp = Array(repeating: Int.max, count: amount + 1)
dp[0] = 0
for i in coins {
if amount < i { continue }
for j in i...amount {
if dp[j - i] != Int.max {
dp[j] = min(dp[j], dp[j - i] + 1)
}
}
}
return dp[amount] == Int.max ? -1 : dp[amount]
}
}
题目2:279.完全平方数
讲解
leetcode
class Solution {
func numSquares(_ n: Int) -> Int {
var dp = Array(repeating: Int.max, count: n + 1)
dp[0] = 0
for j in 1...n {
for i in 1...j {
if j < i * i { break }
dp[j] = min(dp[j], dp[j - i * i] + 1)
}
}
return dp[n]
}
}
题目3: 139.单词拆分
讲解
leetcode
class Solution {
func wordBreak(_ s: String, _ wordDict: [String]) -> Bool {
var dp = Array(repeating: false, count: s.count + 1)
dp[0] = true
for i in 1...s.count {
for word in wordDict {
if i < word.count { continue }
let end = s.index(s.startIndex, offsetBy: i - 1)
let start = s.index(s.startIndex, offsetBy: i - word.count)
let subStr = String(s[start...end])
if dp[i - word.count], subStr == word {
dp[i] = true
}
}
}
return dp[s.count]
}
}
class Solution {
func wordBreak(_ s: String, _ wordDict: [String]) -> Bool {
var dp = Array(repeating: false, count: s.count + 1)
dp[0] = true
for i in 1...s.count {
for j in 0..<i {
let start = s.index(s.startIndex, offsetBy: j)
let end = s.index(s.startIndex, offsetBy: i)
var subStr = String(s[start..<end])
if dp[j] && wordDict.contains(subStr) {
dp[i] = true
}
}
}
return dp[s.count]
}
}