Skip to content

Commit 561b768

Browse files
authored
Create CombinationSumII.java
1 parent 89f33c1 commit 561b768

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Backtracking/CombinationSumII.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//LeetCode 40. Combination Sum II
2+
//Question - https://leetcode.com/problems/combination-sum-ii/
3+
4+
class Solution {
5+
public List<List<Integer>> combinationSum2(int[] nums, int target) {
6+
List<List<Integer>> res = new ArrayList<>();
7+
8+
Arrays.sort(nums);
9+
helper(nums, 0, 0, target, new ArrayList<>(), res);
10+
return res;
11+
12+
}
13+
14+
public void helper(int nums[], int index, int sum, int target, List<Integer> l, List<List<Integer>> res){
15+
if(sum > target) return;
16+
else if(sum == target){
17+
res.add(new ArrayList<>(l));
18+
return;
19+
}
20+
21+
for(int i = index ; i < nums.length ; i++){
22+
if(i > index && nums[i] == nums[i-1]) continue;
23+
24+
l.add(nums[i]);
25+
helper(nums, i + 1, sum + nums[i], target, l, res);
26+
l.remove(l.size()-1);
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)