Skip to content

Commit e8f647c

Browse files
committed
combination sum
1 parent 614c237 commit e8f647c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

combination-sum/eunhwa99.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,25 @@ private void backtrack(int[] candidates, int target, int start, List<Integer> cu
3030
}
3131
}
3232
}
33+
34+
class newSolution{
35+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
36+
List<List<Integer>> result = new ArrayList<>();
37+
backtrack(result, new ArrayList<>(), candidates, target, 0);
38+
return result;
39+
}
40+
41+
private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] candidates, int remain, int start) {
42+
if (remain < 0) return; // 넘치면 종료
43+
if (remain == 0) {
44+
result.add(new ArrayList<>(tempList)); // 정답 조합 발견
45+
return;
46+
}
47+
48+
for (int i = start; i < candidates.length; i++) {
49+
tempList.add(candidates[i]); // 후보 추가
50+
backtrack(result, tempList, candidates, remain - candidates[i], i); // **같은 수를 다시 사용할 수 있으므로 i**
51+
tempList.removeLast(); // 백트래킹 (되돌리기)
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)