Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created February 4, 2020 02:19
Show Gist options
  • Save spurscho/4f56d7cdbd8188b44ca7a45363cbd991 to your computer and use it in GitHub Desktop.
Save spurscho/4f56d7cdbd8188b44ca7a45363cbd991 to your computer and use it in GitHub Desktop.
39. Combination Sum
class Solution {
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
var res = [[Int]]()
var temp = [Int]()
helper(&res, &temp, candidates, 0, target)
return res
}
func helper(_ res: inout [[Int]], _ temp: inout [Int], _ candidates: [Int], _ index: Int, _ target: Int) {
//print("res: \(res), temp: \(temp), candidates: \(candidates), index: \(index), target: \(target)")
if target < 0 { return }
if target == 0 {
res.append(temp)
//print("temp is appended")
return
}
for i in index ..< candidates.count {
if candidates[i] == 0 { continue }
temp.append(candidates[i])
helper(&res, &temp, candidates, i, target - candidates[i]) // 이해안감 왜 target - candidates[i] 인지?
temp.removeLast()
}
}
}
let sol = Solution()
let arr = [2,3,6,7]
print(sol.combinationSum(arr, 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment