1+ class Solution :
2+ def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
3+ result = []
4+
5+ def backtrack (start , current , current_sum ):
6+ if current_sum == target :
7+ result .append (current [:])
8+ return
9+
10+ if current_sum > target :
11+ return
12+
13+ for i in range (start , len (candidates )):
14+ current .append (candidates [i ])
15+ backtrack (i , current , current_sum + candidates [i ])
16+ current .pop ()
17+
18+ backtrack (0 , [], 0 )
19+ return result
20+
21+
22+ """
23+ ================================================================================
24+ 풀이 과정
25+ ================================================================================
26+
27+ 1. 이거 모든 가능한 조합을 찾아야하는데 합이 target을 넘으면 중단되야하네?
28+ 2. 문제는 같은 숫자를 여러 번 쓸 수 있는건데..
29+ 3. 백트래킹으로 접근해야할 것 같은데..
30+
31+
32+ [1차 시도] 백트래킹 (Backtracking)
33+ ────────────────────────────────────────────────────────────────────────────────
34+ 4. 모든 조합을 탐색하되, 조건에 맞지 않으면 가지치기
35+ 5. 같은 숫자를 여러 번 사용할 수 있으므로 재귀 호출 시 같은 인덱스부터 시작
36+ 6. 중복 조합 방지를 위해 start 인덱스 사용
37+
38+ result = []
39+
40+ def backtrack(start, current, current_sum):
41+ # target을 만족하면 결과에 추가
42+ if current_sum == target:
43+ result.append(current[:]) # 복사해서 추가
44+ return
45+
46+ # 가지치기: 합이 target 초과
47+ if current_sum > target:
48+ return
49+
50+ # 조합 탐색
51+ for i in range(start, len(candidates)):
52+ current.append(candidates[i])
53+ # 같은 숫자 재사용 가능하므로 i부터 시작
54+ backtrack(i, current, current_sum + candidates[i])
55+ current.pop() # 백트래킹: 상태 복원
56+
57+ backtrack(0, [], 0)
58+ return result
59+
60+ 7. Example: candidates = [2,3,6,7], target = 7
61+
62+ backtrack(0, [], 0)
63+ ├─ 2 추가 → backtrack(0, [2], 2)
64+ │ ├─ 2 추가 → backtrack(0, [2,2], 4)
65+ │ │ ├─ 2 추가 → backtrack(0, [2,2,2], 6)
66+ │ │ │ └─ 2 추가 → backtrack(0, [2,2,2,2], 8) → 8 > 7 return
67+ │ │ └─ 3 추가 → backtrack(1, [2,2,3], 7) → 7 == 7 ✅ [2,2,3]
68+ │ └─ 3 추가 → backtrack(1, [2,3], 5)
69+ │ └─ ... (탐색 계속)
70+ └─ 7 추가 → backtrack(3, [7], 7) → 7 == 7 ✅ [7]
71+
72+ 8. 시간 복잡도: O(N^(T/M))
73+ - N: candidates 길이
74+ - T: target 값
75+ - M: candidates의 최소값
76+ 9. 공간 복잡도: O(T/M) - 재귀 호출 스택 깊이
77+ """
0 commit comments