Created
January 17, 2017 07:46
-
-
Save jsrikrishna/be995c28f8fe19d200200bb5987a7c76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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