leecode 39. 组合总和

给定一个无重复元素的数组 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]
]

提示:

1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500

/*
 * 39. Combination Sum
 * 题意:找出和为sum的所有组合
 * 难度:Medium
 * 分类:Array, Backtracking
 * 思路:回溯法
 * Tips:向res添加答案时注意要new一个新的List,否则后续循环的操作会影响res中的L; 设置一个start标志,记录上次数组循环到哪了,防止重复集合。
 * 和lc46,lc78做比较,46是排列组合,所以不需要start标志,start标志是为了防止相同元素的组合排列不同而当做了另一种
 */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class leecode200 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(res, path, candidates, target, 0, 0);
        return res;
    }

    public static void backtrack(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int begin) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = begin; i < candidates.length; i++) {
            int rs = sum + candidates[i];
            if (rs > target) {
                break;
            } else {
                path.add(candidates[i]);
                backtrack(res, path, candidates, target, rs, i);
                path.remove(path.size() - 1);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/kpwong/p/14650671.html