Better Backtracking


  • 0
    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);
            bt(res, new ArrayList<Integer>(), candidates, target, 0);
            return res;
        }
        
        public boolean bt(List<List<Integer>> res, List<Integer> candidateList, int[] candidates, int target, int idx) {
            if (target < 0) {
                return false;
            } else if (target == 0) {
                res.add(new ArrayList<Integer>(candidateList));
                return false;
            } else {
                for (int i = idx; i < candidates.length; i++) {
                    candidateList.add(candidates[i]);
                    boolean temp = bt(res, candidateList, candidates, target - candidates[i], i);
                    candidateList.remove(candidateList.size() - 1);
                    if (temp == false) {
                        break;
                    }
                }
                return true;
            }
        }
    }
    

Log in to reply
 

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