回溯算法--LeetCode-39 组合总和、LeetCode-40 组合总和Ⅱ

LeetCode-39 组合总和

题目链接:https://leetcode-cn.com/problems/combination-sum/

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

输入: candidates = [2,3,6,7],target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]

示例 2:

输入: candidates = [2,3,5],target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        combinationSum(candidates, target, 0, new ArrayList<>(), result);
        return result;
    }

    // 回溯算法
    // 1、题目为无重复数组,故不需去重
    // 2、数字可被无限重复选取,故从start本身开始递归
    public static void combinationSum(int[] candidates, int target, int start, List<Integer> temp, List<List<Integer>> result) {
        if (target == 0) {
            result.add(new ArrayList<>(temp));
            return;
        }
        if (target < 0) {
            return;
        }
        for (int i = start; i < candidates.length && candidates[i] <= target; i++) {
            temp.add(candidates[i]);
            combinationSum(candidates, target - candidates[i], i, temp, result);
            temp.remove(temp.size()-1);
        }
    }

LeetCode-40 组合总和Ⅱ

题目链接:https://leetcode-cn.com/problems/combination-sum-ii/

 

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        combinationSum2(candidates, target, 0, new ArrayList<>(), result);
        return result;
    }

    // 回溯算法
    // 1、题目为重复数组,故需要去重
    // 2、数字只能选取一次,故从start+1开始递归
    public static void combinationSum2(int[] candidates, int target, int start, List<Integer> temp, List<List<Integer>> result) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            result.add(new ArrayList<>(temp));
            return;
        }
        for (int i = start; i < candidates.length && candidates[i] <= target; i++) {
            if (i > start && candidates[i] == candidates[i-1]) // 去重
                continue;
            temp.add(candidates[i]);
            combinationSum2(candidates, target - candidates[i], i+1, temp, result);
            temp.remove(temp.size()-1);
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章