
#Backtracking 풀이
class Solution{
public List<List<Integer>> combinationSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
backtrack(list, new ArrayList<>(), nums, target, 0);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
if(remain < 0) return;
else if(remain == 0) list.add(new ArrayList<>(tempList));
else{
for(int i = start; i < nums.length; i++){
tempList.add(nums[i]);
backtrack(list, tempList, nums, remain - nums[i], i); // not i + 1 because we can reuse same elements
tempList.remove(tempList.size() - 1);
}
}
}
}
'LeetCode > Array' 카테고리의 다른 글
[Easy] 217. Contains Duplicate (0) | 2022.09.13 |
---|---|
[Medium] 238. Product of Array Except Self (애플 코딩 테스트 문제) (0) | 2022.09.08 |
[Medium] 53. Maximum Subarray (0) | 2022.09.04 |
[Easy] 35. Search Insert Position (0) | 2022.09.01 |
[Easy]1672. Richest Customer Wealth (0) | 2022.08.27 |