hello-algo/codes/swift/chapter_dynamic_programming/unbounded_knapsack.swift
nuomi1 7359a7cb4b
Review Swift codes (#1150)
* feat(swift): review for chapter_computational_complexity

* feat(swift): review for chapter_data_structure

* feat(swift): review for chapter_array_and_linkedlist

* feat(swift): review for chapter_stack_and_queue

* feat(swift): review for chapter_hashing

* feat(swift): review for chapter_tree

* feat(swift): add codes for heap article

* feat(swift): review for chapter_heap

* feat(swift): review for chapter_graph

* feat(swift): review for chapter_searching

* feat(swift): review for chapter_sorting

* feat(swift): review for chapter_divide_and_conquer

* feat(swift): review for chapter_backtracking

* feat(swift): review for chapter_dynamic_programming

* feat(swift): review for chapter_greedy

* feat(swift): review for utils

* feat(swift): update ci tool

* feat(swift): trailing closure

* feat(swift): array init

* feat(swift): map index
2024-03-20 21:15:39 +08:00

63 lines
1.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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)")
}
}