Simple DFS solution JAVA


  • 0
    A
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if (candidates == null || candidates.length == 0){
                return res;
            }
            Arrays.sort(candidates);
            helper (res,candidates,target,new ArrayList<Integer>(),0,0);
            return res;
        }
        
        public void helper (List<List<Integer>> res, int[] candidates, int target, List<Integer> ls,int sum,int pos){
            if (sum == target){
                res.add(new ArrayList<Integer>(ls));
                return;
            }
            for (int i = pos; i < candidates.length; i++){
                if ((sum + candidates[i]) > target){
                    break;  
                }
                ls.add(candidates[i]);
                helper (res,candidates,target,ls,sum+candidates[i],i);
                ls.remove(ls.size() - 1);
            }
        }
    }

Log in to reply
 

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