Skip to content

Commit bff76a0

Browse files
authored
feat: add combination sum solution
1 parent bdc238b commit bff76a0

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

β€Žcombination-sum/kangdaia.pyβ€Ž

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution:
2+
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
3+
"""
4+
μ£Όμ–΄μ§„ 숫자 λͺ©λ‘μ—μ„œ λͺ©ν‘œν•˜λŠ” 합을 λ§Œλ“€ 수 μžˆλŠ” 쑰합을 μ°ΎλŠ” ν•¨μˆ˜
5+
μˆ«μžλŠ” 동일 숫자λ₯Ό μ—¬λŸ¬λ²ˆ μ‚¬μš©ν•΄λ„ 됨
6+
7+
방법:
8+
DFS 방식을 μ‚¬μš©ν•¨.
9+
- ν˜„μž¬ 인덱슀λ₯Ό κΈ°μ€€μœΌλ‘œ,
10+
(선택지)
11+
ν˜„μž¬ μœ„μΉ˜μ˜ μˆ«μžκ°’μ„ ν˜„μž¬ 쑰합에 포함할지
12+
- ν˜„μž¬ 합을 λ§Œλ“€κΈ° μœ„ν•΄ 남은 κ°’ - ν˜„μž¬ 값이 0 이상이면 포함 κ°€λŠ₯
13+
- ν˜„μž¬ 값을 μ—¬λŸ¬λ²ˆ μ“Έ 수 μžˆκΈ°μ— 인덱슀λ₯Ό λŠ˜λ¦¬μ§€ x
14+
ν˜„μž¬ μœ„μΉ˜μ˜ μˆ«μžκ°’μ„ ν˜„μž¬ 쑰합에 ν¬ν•¨ν•˜μ§€ μ•Šμ„μ§€
15+
- 이 μΈλ±μŠ€κ°€ λͺ©λ‘κΈΈμ΄λ₯Ό λ„˜μ–΄κ°€λ©΄ μ•ˆλ¨
16+
- ν•©μ˜ λ‚˜λ¨Έμ§€ 값이 0이면 λͺ©ν‘œμ— λ„λ‹¬ν•œκ²ƒ -> μ‘°ν•© λͺ©λ‘μ— 포함
17+
18+
Args:
19+
candidates (list[int]): μ‚¬μš©κ°€λŠ₯ν•œ 숫자 λͺ©λ‘. unique
20+
target (int): λͺ©ν‘œν•˜λŠ” ν•©
21+
22+
Returns:
23+
list[list[int]]: λͺ©ν‘œν•˜λŠ” 합을 λ§Œλ“€ 수 μžˆλŠ” κ°€λŠ₯ν•œ 숫자 μ‘°ν•©. unique
24+
"""
25+
combinations = list()
26+
def getCombination(idx, remain, path):
27+
"""
28+
ν˜„μž¬ ν•¨μˆ˜μ—μ„œ μž¬κ·€λ₯Ό μœ„ν•œ helper ν•¨μˆ˜
29+
"""
30+
if remain == 0:
31+
combinations.append(path)
32+
return
33+
if idx < len(candidates):
34+
curr = candidates[idx]
35+
if remain - curr >= 0:
36+
getCombination(idx, remain - curr, path + [curr])
37+
getCombination(idx + 1, remain, path)
38+
return
39+
getCombination(0, target, [])
40+
return combinations

0 commit comments

Comments
Β (0)