- LeetCode 최소 하루에 하나는 풀자는 마인드
- 사용언어: JAVA
39. Combination Sum
풀이
- 방법: backtrack을 사용하여 sum 이 target과 같거나 클때까지 반복, 같을 때를 체크
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> current = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
backtrack(current, result, target, candidates, 0, 0);
return result;
}
private void backtrack (List<Integer> current, List<List<Integer>> result,
int target, int[] candidates, int sum, int start)
{
if(sum == target){
result.add(new ArrayList<>(current));
return;
}
if(sum > target) return;
for(int i = start; i < candidates.length; i++){
current.add(candidates[i]);
backtrack(current, result, target, candidates, sum + candidates[i], i);
current.remove(current.size() - 1);
}
return;
}
}