Easy Java backtracking solution..


  • 0
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            
            List<List<Integer>> res = new ArrayList<>();
            
            helper(res, new ArrayList<>(), candidates, target, 0);
            
            return res;
            
        }
        
        private void helper(List<List<Integer>> res, List<Integer> com, int[] candidates, int target, int start) {
            
            if(target < 0 || start >= candidates.length) {
                return;
            }
            if(target == 0) {
                res.add(new ArrayList<>(com));
                return;
            }
            
            for(int i = start; i < candidates.length; i++) {
                
                int num = candidates[i];
                com.add(num);
                helper(res, com,  candidates, target-num, i);
                com.remove(com.size()-1);
            }
            
        }
    

Log in to reply
 

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