DFS Java solution


  • 1
    M
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        List<Integer> sublist = new ArrayList<Integer>();
        
        dfs(candidates, target, 0, sublist, list);
        return list;
    }
    
    public void dfs(int[] candidates, int target, int start, List<Integer> sublist, List<List<Integer>> list){
        if(target == 0 && ! list.contains(sublist) ){
            list.add(sublist);
            return;
        }
        
        for(int i = start; i < candidates.length; i++){
            if( i > start && candidates[i] == candidates[i-1]) continue;
            List<Integer> temp = new ArrayList<Integer>();
            temp.addAll(sublist);
            temp.add(candidates[i]);
            
            if(candidates[i] > target) break;
            
            dfs(candidates, target - candidates[i], i + 1, temp, list);
        }
    }

Log in to reply
 

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