Java Solution Using Backtracking.


  • 0
    C
       public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<List<Integer>> result  = new ArrayList<>();
            List<Integer> lst = new ArrayList<>();
            helper(result,lst, candidates,target,0);
            return result;
        }
        
        public void helper(List<List<Integer>> res, List<Integer> list, int[] cand, int tar, int start){
            if(tar<0)
                return;
            if(tar==0){
                res.add(list);
                return;
            }
            for(int i=start; i<cand.length&&tar>=cand[i]; i++){
                list.add(cand[i]);
                helper(res, new ArrayList(list), cand, tar-cand[i],i);
                list.remove(list.size()-1);
            }
                
        }

Log in to reply
 

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