Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.The same number may be chosen from candidates an unlimited number of times.The combinations themselves must be in sorting order and not contain duplicate combinations.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
CombinationA > CombinationB iff (a1 > b1) OR (a1 = b1 AND a2 > b2) OR ... (a1 = b1 AND a2 = b2 AND ... ai = bi AND ai+1 > bi+1)
The below code that i have written in java language uses backtracking and gets all unique combinations and adds them into res variable.
But I am not able to figure out how each of these combinations will be sorted. Simply sorting each combination would blow up the time complexity in my opinion.
Input: A = [2,3,6,7], target = 7 Output: [[2,2,3],[7]]
By sorted I mean [3,2,2] cannot be as a valid combination
public ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> A, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> comb = new ArrayList<Integer>();
generate(0, A, target, comb, res);
return res;
}
public static void generate(int idx, ArrayList<Integer> A, int target, ArrayList<Integer> comb, ArrayList<ArrayList<Integer>> res) {
if(target < 0) return;
if(target == 0) {
res.add(new ArrayList<Integer>(comb));
return;
}
for(int i=idx; i<A.size(); i++) {
comb.add(A.get(i));
generate(i, A, target - A.get(i), comb, res); // backtracking step
comb.remove(comb.size() - 1);
}
}}