Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created May 7, 2019 06:12
Show Gist options
  • Save derekli66/d2bd267ddd53c96af7d04491f522512a to your computer and use it in GitHub Desktop.
Save derekli66/d2bd267ddd53c96af7d04491f522512a to your computer and use it in GitHub Desktop.
This gist is the practice of knapsack problem. The solution without optimization by using memoization.
import Foundation
func knapsack(_ weights: Array<Int>,_ values: Array<Int>,_ index: Int,_ remainingWeight: Int) -> Int {
if (index < 0) { return 0 }
var choosedValue: Int = 0
if (remainingWeight >= weights[index]) {
// Choose
choosedValue = values[index] + knapsack(weights, values, index - 1, remainingWeight - weights[index])
}
// Not choose
let notChoosedValue = knapsack(weights, values, index - 1, remainingWeight)
return max(choosedValue, notChoosedValue)
}
let weights = [2, 5, 3]
let values = [10, 1, 2]
let weightLimit = 2
let mostValue = knapsack(weights, values, weights.count - 1, weightLimit)
print("[Knapsack] The most value can be carried is \(mostValue)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment