Skip to content

Commit faf6d98

Browse files
committed
combination-sum
1 parent f6ed285 commit faf6d98

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

combination-sum/socow.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
문제 요약
3+
- candidates 배열에서 숫자를 무제한 사용하여 합이 target이 되는 모든 조합 찾기
4+
5+
아이디어
6+
- 백트래킹: i번째 인덱스부터 탐색하여 중복 조합 방지
7+
- 같은 숫자 재사용 가능 → 재귀 시 인덱스 i 유지
8+
- 정렬 후 target 초과 시 break로 가지치기
9+
10+
시간복잡도: O(N^(T/M)) - N: candidates 길이, T: target, M: 최소값
11+
공간복잡도: O(T/M) - 재귀 깊이
12+
"""
13+
14+
class Solution:
15+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
16+
result = []
17+
sol = []
18+
candidates.sort()
19+
n = len(candidates)
20+
21+
def backtrack(start, cur_sum):
22+
if cur_sum == target:
23+
result.append(sol.copy())
24+
return
25+
26+
for i in range(start, n):
27+
if cur_sum + candidates[i] > target:
28+
break
29+
sol.append(candidates[i])
30+
backtrack(i, cur_sum + candidates[i])
31+
sol.pop()
32+
33+
backtrack(0, 0)
34+
return result

0 commit comments

Comments
 (0)