Java backtracking recursive w/ comments


  • 0
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> list = new ArrayList<>();
            if (candidates == null || candidates.length == 0)
                return list;
            Arrays.sort(candidates);
            combinationSum(list, new ArrayList<>(), candidates, 0, 0, target);
            return list;
        }
        
        private void combinationSum(List<List<Integer>> list, List<Integer> comb, int[] candidates, int i,int sum, int target) {
            if (sum == target) {
                list.add(new ArrayList<>(comb));
                return;
            }
            if (i == candidates.length) // out of bondary failure
                return;
            if (sum + candidates[i] <= target) { // add candidates[i] if by adding it, sum is not > target
                comb.add(candidates[i]);
                combinationSum(list, comb, candidates, i, sum + candidates[i], target);
                comb.remove(comb.size() - 1);
            }
            combinationSum(list, comb, candidates, i + 1, sum, target); // do not add candidates[i]
        } 
    }

Log in to reply
 

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