Simple and short java solution


  • 0
    L
    public class Solution {
    List<List<Integer>> results=new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates.length==0||candidates==null) return results;
        Arrays.sort(candidates);
        dfs(new ArrayList<Integer>(),candidates,0,target);
        return results;
    }
    public void dfs(List<Integer> cur,int[] candidates,int start,int target){
        if(target==0) results.add(new ArrayList<Integer>(cur));
        else if(target>0){
            for(int i=start;i<candidates.length&&candidates[i]<=target;i++){
                if(i==start||candidates[i]!=candidates[i-1]){
                    cur.add(candidates[i]);
                    dfs(cur,candidates,i+1,target-candidates[i]);
                    cur.remove(cur.size()-1);
                }
            }
        }
    }
    

    }


Log in to reply
 

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