Skip to content

Instantly share code, notes, and snippets.

@jsrikrishna
Created January 17, 2017 07:46
Show Gist options
  • Save jsrikrishna/be995c28f8fe19d200200bb5987a7c76 to your computer and use it in GitHub Desktop.
Save jsrikrishna/be995c28f8fe19d200200bb5987a7c76 to your computer and use it in GitHub Desktop.
public static void main(String[] args) {
int[] data = {1,2,3,4,5};
int target = 6;
int k = 3;
System.out.println("combinations are " + kcombinationSum(data, target, k));
}
public static List<List<Integer>> kcombinationSum(int[] data, int target, int k){
Arrays.sort(data);
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
kcombinationSumUtil(data, res, temp, target, 0, k);
return res;
}
public static void kcombinationSumUtil(int[] data, List<List<Integer>> res, List<Integer> temp, int target, int start, int k){
if(target == 0 && temp.size() == k){
res.add(new ArrayList<>(temp));
}
else {
for(int i=start; i<data.length && target-data[i] >=0 ; i++){
temp.add(data[i]);
kcombinationSumUtil(data, res, temp, target - data[i], i+1, k); // i+1, because same number cannot be used twice
temp.remove(temp.size()-1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment