1

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);
    }
}}
Aditya
  • 950
  • 8
  • 37
  • Wouldn't the result already be in sorted order? Since you're processing the input array (Which is already in sorted form, I believe. If not you need to just sort this input array before starting the processing). The output will always show sorted form. – Kishore Bandi Aug 13 '21 at 19:36
  • There are more constraints to the problem. I have mentioned them in the question. I have tried sorting it but fails for input A : [ 8, 10, 6, 11, 1, 16, 8 ] target : 28 – Aditya Aug 13 '21 at 19:55
  • 1
    Please try to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Karl Knechtel Aug 13 '21 at 20:25
  • @Aditya I understand, but why not sort the input, remove duplicates and then invoke your `combinationSum` API. So no matter what the input is, `A : [ 8, 10, 6, 11, 1, 16, 8 ] target : 28` you'll always pass `A : [ 1, 6, 8, 10, 11, 16 ] target : 28`. This will ensure you'll not have duplicates and the output will be sorted. Since the initial sort complexity is `nlogn` it will not effect your current complexity in anyway. – Kishore Bandi Aug 14 '21 at 07:21

0 Answers0