Java Backtracking Solution, Easy to understand


  • 2
    X
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
            add(res, new ArrayList<Integer>(), candidates, 0, target);
            return res;
        }
        
        private void add(ArrayList<List<Integer>> res, ArrayList<Integer> list, int[] candidates, int start, int target){
            if(target < 0)  return;
            else if(target == 0){
                res.add(list);
                return;
            }
            for(int i=start; i<candidates.length; ++i){
                ArrayList<Integer> temp = new ArrayList<Integer>(list);
                temp.add(candidates[i]);
                add(res, temp, candidates, i, target-candidates[i]);
            }
        }
    }

Log in to reply
 

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