美文网首页
39. & 40. Combination Sum I & II

39. & 40. Combination Sum I & II

作者: Super_Alan | 来源:发表于2018-05-09 01:13 被阅读0次
39. Combination Sum 题目截图
public List<List<Integer>> combinationSum(int[] candidates, int target) {
    ArrayList<List<Integer>> res = new ArrayList<>();
    if (candidates == null || candidates.length == 0) {
        return res;
    }
    // Arrays.sort(candidates);
    backtracking(target, 0, candidates, new ArrayList<Integer>(), res);

    return res;
}

private void backtracking(int target, int index, int[] nums, ArrayList<Integer> path, ArrayList<List<Integer>> res) {
    if (target == 0) {
        res.add(new ArrayList<Integer>(path));
        return;
    }
    if (target < 0 || index >= nums.length) {
        return;
    }

    for (int i = index; i < nums.length; i++) {
        path.add(nums[i]);
        // item 可以重复使用,故 next index 为 i
        backtracking(target - nums[i], i, nums, path, res);
        path.remove(path.size() - 1);
    }
}

40. Combination Sum II 题目截图
public List<List<Integer>> combinationSum2(int[] nums, int target) {
    ArrayList<List<Integer>> res = new ArrayList<>();
    if (nums == null || nums.length == 0) {
        return res;
    }

    Arrays.sort(nums);
    backtracking(target, 0, nums, new ArrayList<Integer>(), res);

    return res;
}

private void backtracking(int target, int index, int[] nums, ArrayList<Integer> path, ArrayList<List<Integer>> res) {
    if (target == 0) {
        res.add(new ArrayList<Integer>(path));
        return;
    }
    if (target < 0 || index >= nums.length) {
        return;
    }
    for (int i = index; i < nums.length; i++) {

        // 该 for 循环,是对 current path next item 的尝试;
        // 当 i>index 且nums[i] == nums[i - 1], 说明这个 item 对 current path next item 的尝试已经在之前完成过了,
        // 就不需要,也不应该再尝试了。
        if (i > index && nums[i] == nums[i - 1]) {
            continue;
        }
        path.add(nums[i]);
        backtracking(target - nums[i], i + 1, nums, path, res);
        path.remove(path.size() - 1);
    }
}

相关文章

网友评论

      本文标题:39. & 40. Combination Sum I & II

      本文链接:https://www.haomeiwen.com/subject/pcbgrftx.html