-
Notifications
You must be signed in to change notification settings - Fork 6
/
CombinationSum.java
42 lines (32 loc) · 1.21 KB
/
CombinationSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.shivaprasad.january.day30;
import java.util.ArrayList;
import java.util.List;
public class CombinationSum {
public static void main(String[] args) {
List<List<Integer>> res = combinationSum(new int[]{2,3,5},8);
System.out.println(res);
}
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> output = new ArrayList<>();
combinationsGenerator(candidates,0,target,new ArrayList<Integer>(),output);
return output;
}
private static void combinationsGenerator(int[] nums, int currentIndex, int target, ArrayList<Integer> currentSet, List<List<Integer>> output) {
if(target == 0)
{
output.add(new ArrayList<>(currentSet));
return;
}
if(currentIndex>=nums.length)
return;
int currentVal = nums[currentIndex];
if(target>= currentVal)
{
currentSet.add(currentVal);
combinationsGenerator(nums,currentIndex,target-currentVal,currentSet,output);
currentSet.remove(currentSet.size()-1);
}
combinationsGenerator(nums,currentIndex+1,target,currentSet,output);
return;
}
}