A fast , esay and more understanding java solution


  • 0
    D

    ``

    int index = 0;
    
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        for(int i = index;i<candidates.length;i++) {
            if(i >0 && candidates[i] == candidates[i-1]) continue;
            if(candidates[i] > target) break;
            if(candidates[i] == target){
                List<Integer> integers = new ArrayList<>();
                integers.add(candidates[i]);
                result.add(integers);
                continue;
            }
            index = i;//ensure not duplicate
            List<List<Integer>> childResult =  combinationSum(candidates , target - candidates[i]);
            if(childResult.isEmpty()) continue;
            for (List<Integer> list : childResult) {
                list.add(candidates[i]);
                result.add(list);
            }
        }
        return result;
    }
    

    ``


Log in to reply
 

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