[Leetcode] 40. Combination Sum II β
#μ‘°ν©
Problem β
μ£Όμ΄μ§ λ°°μ΄μ μμλ€μ ν©νμ¬ target
μ κ°μ΄λλ μ‘°ν©μ ꡬνμ¬νλ λ¬Έμ
Solution β
combination sum μμμ μ€λ³΅μ λΊ λ°©λ²
- νμ¬ μΈλ±μ€λ₯Ό μΆκ°νμ§μκ³ λμ€λ₯Ό μ΄μ΄λκ°λ©΄λλ€.
JS Code β
js
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function (candidates, target) {
let answer = []
const dfs = function (comb, sum, curr) {
if (sum === target) {
answer.push([...comb])
return
}
for(let nextCurr = curr ; nextCurr < candidates.length; ++nextCurr) {
if (curr < nextCurr && candidates[nextCurr] === candidates[nextCurr - 1]) continue
const pick = candidates[nextCurr]
if (target < sum + pick) break
comb.push(pick)
dfs(comb, sum + pick, nextCurr + 1)
comb.pop()
}
}
candidates.sort((a, b) => a - b)
dfs([], 0, 0)
return answer
}