Java backtracking concise solution with explanation


  • 0
    G

    public class CombinationSum {

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> ans = new ArrayList<>();
        backtrack(target, candidates, ans, new ArrayList<>(), 0);
        return ans;
    }
    
    public void backtrack(int target, int[] candidates, List<List<Integer>> ans, List<Integer> branch, int start) {
        if (target == 0) {
            ans.add(new ArrayList<>(branch));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            if (target - candidates[i] >= 0) {
                branch.add(candidates[i]);
                // Continue to start from i + 1 to avoid duplication
                backtrack(target - candidates[i], candidates, ans, branch, i + 1);
                // If we come to here, no valid result OR combination is done, backtrack the last element.
                branch.remove(branch.size() - 1);
                // Remove duplicated elements from i to avoid duplication after backtracking
                // Eg. given candidate set 10,1,2,7,6,1,5 and target 8, it will eliminate the second [1, 2, 5]
                while (i + 1 < candidates.length && candidates[i] == candidates[i + 1]) {
                    i++;
                }
            }
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.