39.Combination Sum

1-Backtracking

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        helper(ans, new ArrayList<>(), candidates, 0, 0, target);
        return ans;
    }

    public void helper(List<List<Integer>> ans, List<Integer> comb, int[] candidates, int curPos, int curSum, int target){
        if(curSum > target)
            return ;
        if(curSum == target){
            //comb.add(candidates[curPos]);
            ans.add(new ArrayList<>(comb));
            return;
        }
        else{
            for(int i = curPos; i < candidates.length; i++){
                comb.add(candidates[i]);
                helper(ans, comb, candidates, i,  curSum + candidates[i], target);
                comb.remove(comb.size() - 1);
            }
            return;
        }
    }
}
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        combinationSum(result,new ArrayList<Integer>(),candidates,target,0);
        return result;
    }
    public void combinationSum(List<List<Integer>> result, List<Integer> cur, int[] candidates, int target,int start) {
        if (target > 0) {
            for (int i = start;i < candidates.length;i++) { // not using the condition "target >= candidates[i]"
                cur.add(candidates[i]);
                combinationSum(result, cur, candidates, target-candidates[i],i);
                cur.remove(cur.size() - 1);
            }
        }
        if (target == 0) result.add(new ArrayList<Integer>(cur));
    }
}

results matching ""

    No results matching ""