数组中和为m的子数组

分数组中的元素,可以重复取和不能重复取两种情况,只需修改回溯的指针值(可重复取为i,不可重复取为i+1)

计算之前要先对数组进行排序

Arrays.sort(candidates);
public static void backtrack(int[] candidates, int target, int sum, int begin,List<Integer> path,  List<List<Integer>> res) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = begin; i < candidates.length; i++) {
            if (i > begin && candidates[i] == candidates[i - 1]) continue;
            int count = candidates[i] + sum;
            if (count <= target) {
                path.add(candidates[i]);
                backtrack(candidates, target, count, i + 1, path, res);//如果每个数可以重复拿,改为i
                path.remove(path.size() - 1);
            } else {
                break;
            }
        }
    }

运行结果

//nums = {2, 7, 6, 3, 1};target=9;
//可重复取
[[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 2, 3], [1, 1, 1, 2, 2, 2], [1, 1, 1, 3, 3], [1, 1, 1, 6], [1, 1, 2, 2, 3], [1, 1, 7], [1, 2, 2, 2, 2], [1, 2, 3, 3], [1, 2, 6], [2, 2, 2, 3], [2, 7], [3, 3, 3], [3, 6]]
//不可重复取
[[1, 2, 6], [2, 7], [3, 6]]
posted @ 2021-04-28 18:53  笨鸟贤妃  阅读(57)  评论(0)    收藏  举报