Skip to content

Instantly share code, notes, and snippets.

@possen
Created November 11, 2015 00:32
Show Gist options
  • Save possen/37b0dc76829efbae6836 to your computer and use it in GitHub Desktop.
Save possen/37b0dc76829efbae6836 to your computer and use it in GitHub Desktop.
//
// Description: Finds the sum of all elements that add up to the target value using dynamic programming.
// Note: input array must be non negative and constrained to a reasonable ranage because it uses target+1 memory
//
// Language: Swift
//
// Author: Paul Ossenbruggen
// Date: Nov 10, 2015
//
import Foundation
func countSubElementsThatAddUpToTargetDP(target : Int, array : [Int]) -> Int {
var numWaysToSumToN = [Int](count: target + 1, repeatedValue: 0)
numWaysToSumToN[0] = 1
for val in array {
let prevTarget = target - val
if prevTarget < 0 {
continue
}
for num in (0...prevTarget).reverse() {
numWaysToSumToN[num + val] += numWaysToSumToN[num]
}
}
print(numWaysToSumToN)
return numWaysToSumToN[target]
}
countSubElementsThatAddUpToTargetDP(9, array: [1, 2, 3, 4, 5, 6, 7, 8, 9])
countSubElementsThatAddUpToTargetDP(9, array: [9, 5, 2, 4, 3, 9, 2])
countSubElementsThatAddUpToTargetDP(9, array: [1, 3, 2, 5, 4, 9])
countSubElementsThatAddUpToTargetDP(9, array: [1, 3, 2, 5, 4, 6])
countSubElementsThatAddUpToTargetDP(9, array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment