You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/zh-hant/codes/swift/chapter_dynamic_programming/unbounded_knapsack.swift

64 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: unbounded_knapsack.swift
* Created Time: 2023-07-15
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
func unboundedKnapsackDP(wgt: [Int], val: [Int], cap: Int) -> Int {
let n = wgt.count
// dp
var dp = Array(repeating: Array(repeating: 0, count: cap + 1), count: n + 1)
//
for i in 1 ... n {
for c in 1 ... cap {
if wgt[i - 1] > c {
// i
dp[i][c] = dp[i - 1][c]
} else {
// i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1])
}
}
}
return dp[n][cap]
}
/* */
func unboundedKnapsackDPComp(wgt: [Int], val: [Int], cap: Int) -> Int {
let n = wgt.count
// dp
var dp = Array(repeating: 0, count: cap + 1)
//
for i in 1 ... n {
for c in 1 ... cap {
if wgt[i - 1] > c {
// i
dp[c] = dp[c]
} else {
// i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
}
}
}
return dp[cap]
}
@main
enum UnboundedKnapsack {
/* Driver Code */
static func main() {
let wgt = [1, 2, 3]
let val = [5, 11, 15]
let cap = 4
//
var res = unboundedKnapsackDP(wgt: wgt, val: val, cap: cap)
print("不超過背包容量的最大物品價值為 \(res)")
//
res = unboundedKnapsackDPComp(wgt: wgt, val: val, cap: cap)
print("不超過背包容量的最大物品價值為 \(res)")
}
}