Skip to content

Commit 7285a5c

Browse files
committed
combination-sum solved
1 parent 5dba61d commit 7285a5c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

β€Žcombination-sum/kut7728.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
///κ³ μœ ν•œ μ •μˆ˜λ°°μ—΄μ˜ candidate와 λͺ©ν‘œ μ •μˆ˜ targetκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ,
2+
///μš”μ†Œλ“€μ„ λ”ν•΄μ„œ target을 λ§Œλ“€μˆ˜ μžˆλŠ” candidate의 μœ λ‹ˆν¬ν•œ μ‘°ν•© λͺ©λ‘μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.
3+
///- μ–΄λ–€ μˆœμ„œλ‘œλ“  쑰합을 λ°˜ν™˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
4+
///- ν›„λ³΄μ—μ„œ 같은 숫자λ₯Ό λ¬΄μ œν•œμœΌλ‘œ 선택할 수 μžˆμŠ΅λ‹ˆλ‹€.
5+
///- μ„ νƒν•œ 숫자 쀑 ν•˜λ‚˜ μ΄μƒμ˜ λΉˆλ„κ°€ λ‹€λ₯Έ 경우 두 쑰합은 κ³ μœ ν•œ μ‘°ν•©μž…λ‹ˆλ‹€.
6+
///- ν…ŒμŠ€νŠΈ μΌ€μ΄μŠ€λŠ” μ£Όμ–΄μ§„ μž…λ ₯에 λŒ€ν•΄ ν•©μ‚°λ˜λŠ” 고유 μ‘°ν•©μ˜ μˆ˜κ°€ 150개 미만이 λ˜λ„λ‘ μƒμ„±λ©λ‹ˆλ‹€.
7+
///Ex) candidate [2, 3, 6, 7] target = 7 -> [[2, 2, 3], [7]]
8+
9+
10+
class Solution {
11+
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
12+
result: [[Int]] = []
13+
nums: [Int] = []
14+
15+
func dfs(_ start: Int, _ total: Int) {
16+
//νƒ€κ²Ÿμ— μ μ€‘ν•˜λ©΄ result둜 볡사
17+
if total == target {
18+
result.append(nums)
19+
return
20+
}
21+
22+
//합이 νƒ€κ²Ÿλ³΄λ‹€ 크닀면 κ·Έλƒ₯ μ’…λ£Œ
23+
if total > target {
24+
return
25+
}
26+
27+
//startλΆ€ν„° μ‹œμž‘ν•˜λŠ”κ²ƒμ€ 이전 μš”μ†Œλ“€μ— λŒ€ν•œ 쑰합은 이미 ν…ŒμŠ€νŠΈν–ˆκΈ° λ•Œλ¬Έ
28+
for i in start..<candidates.count {
29+
nums.append(candidates[i])
30+
dfs(i, total + candidates[i])
31+
nums.removeLast()
32+
}
33+
}
34+
35+
dfs(0, 0)
36+
return result
37+
}
38+
}

0 commit comments

Comments
Β (0)