想要精通算法和SQL的成长之路 - 组和总和系列问题

想要精通算法和SQL的成长之路 - 组和总和系列问题

前言

想要精通算法和SQL的成长之路 - 系列导航

一. 组合总和

原题链接

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的所有不同组合 ,并以列表形式返回。你可以按任意顺序返回这些组合。

candidates 中的同一个数字可以无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

  • 输入:candidates = [2,3,6,7], target = 7
  • 输出:[[2,2,3],[7]]

这种穷举组合的题目,都是回溯的一些经典案例。本题目中比较值得注意的一点是:

  • 同一个数字可以无限制重复被选取。也就是说,我们每层递归遍历数组的时候,我们开始遍历的位置就非常重要了。

1.1 递归结束条件

我们递归过程中,肯定有一个变量sum,代表我们当前添加的元素总和是多少。那么递归结束条件有两个:

  • sum > target 。不符合条件,剪枝。直接return
  • sum=target。符合条件,将当前结果加入到结果集中。

1.2 递归过程

首先,由于元素可重复使用。因此我们每层遍历的起始位置可以和上一层相同注意: for循环的起点不能每次都从0开始,因为这样会导致结果的重复。

void backtrack(int[] candidates, int target, int index, int sum, ArrayDeque<Integer> tmp) {
	for (int i = index; i < candidates.length; i++) {
		// 超过target了,直接剪枝,后面都不需要遍历了,不过这里要求数组是从小大大排序的。
	    if (sum + candidates[i] > target) {
	        break;
	    }
	    tmp.addLast(candidates[i]);
	    backtrack(candidates, target, i, sum + candidates[i], tmp);
	    tmp.removeLast();
	}
}

由于要剪枝,因此我们需要对数组进行排序。那么最终的完整代码就是:

public class Main39 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        // 排序,方便后面的剪枝
        Arrays.sort(candidates);
        backtrack(candidates, target, 0, 0, new ArrayDeque<>());
        return res;
    }

    void backtrack(int[] candidates, int target, int index, int sum, ArrayDeque<Integer> tmp) {
        // 当前和超过了目标值,剪枝
        if (sum > target) {
            return;
        }
        // 符合条件,加入结果集并返回
        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            // 当前和超过了目标值,剪枝
            if (sum + candidates[i] > target) {
                break;
            }
            tmp.addLast(candidates[i]);
            // 这里不是传入i+1,而是传入i,代表的就是当前元素可以重复使用
            backtrack(candidates, target, i, sum + candidates[i], tmp);
            // 回溯
            tmp.removeLast();
        }
    }
}

二. 组合总和 II

原题链接
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

在第一题的基础上,有两个改变就是:

  • candidates 中的每个数字在每个组合中只能使用一次 。
  • candidates 数组可能包含重复元素。

那么很简单,我们只需要在第一题的基础上做出更改即可:

针对第一点:去重for循环增加判断。

if (i > index && candidates[i] == candidates[i - 1]) {
    continue;
}

针对第二点:每层递归的for循环起始下标会+1

那么最终代码如下:

public class Main40 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        // 排序,方便后面的剪枝
        Arrays.sort(candidates);
        backtrack(candidates, target, 0, 0, new ArrayDeque<>());
        return res;
    }

    void backtrack(int[] candidates, int target, int index, int sum, ArrayDeque<Integer> tmp) {
        // 当前和超过了目标值,剪枝
        if (sum > target) {
            return;
        }
        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            // 当前和超过了目标值,剪枝
            if (sum + candidates[i] > target) {
                break;
            }
            // 去重
            if (i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            tmp.addLast(candidates[i]);
            // 传入 i+1,当前元素只能用一次
            backtrack(candidates, target, i + 1, sum + candidates[i], tmp);
            tmp.removeLast();
        }
    }
}

三. 组合总和 III

原题链接
找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:

  1. 只使用数字1到9
  2. 每个数字最多使用一次。
  • 输入: k = 3, n = 9
  • 输出: [[1,2,6], [1,3,5], [2,3,4]]

题目信息看起来很短,但是呢,要求到不少:

  1. 首先你的结果集,必须是k个数字,总和为n。那么你在写判断的时候,就有两个if判断。
  2. 其次数字范围给你定死了,[1,9],并且只能使用一次。那么就要做到去重。

第二点不难理解,而且在实际编码的时候,也不需要做去重操作,因为我们肯定是按照[1,9]进行遍历的,每个数字就遍历到一次,本身不存在重复的可能。

然后再说下第一点,为什么要说需要两个if判断?用伪代码来解释就是:

if(当前集合个数==k){
	if(当前集合总和==n){
		加入到结果集
	}
	return
}

为什么不能直接合并成一个if呢?

if(当前集合个数==k && 当前集合总和==n){
	加入到结果集并return
}

这两者的区别就在于return的位置。先说下第一个代码的好处:

  • 当遍历过程中,已经满足了集合个数为k的话,无论当前的集合是否满足题目要求,你都不应该继续往后遍历了(添加元素),应该直接return
  • 而第二个代码的缺点:可能会出现集合总和满足条件,但是个数大于规定条件的情况。

那么我们就知道代码怎么写了:

public class Main216 {
    List<List<Integer>> res = new ArrayList<List<Integer>>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        if (k == 0 || n < 1) {
            return res;
        }
        backtrack(n, k, 1, new ArrayDeque<>(), 0);
        return res;
    }

    void backtrack(int n, int k, int curValue, Deque<Integer> path, int sum) {
        if (sum > n) {
            return;
        }
        // 递归终止条件
        if (k == path.size()) {
            if (sum == n) {
                res.add(new ArrayList<>(path));
            }
            return;
        }
        // 递归的工作
        // 参考组合77的优化,区别就是,该题的数字范围是[1,9]
        for (int i = curValue; i <= 9; i++) {
            // 将当前值加入到临时集中,开启下一层递归
            path.addLast(i);
            sum += i;
            backtrack(n, k, i + 1, path, sum);
            // 回溯,注意,和也应该要跟着回溯。
            path.removeLast();
            sum -= i;
        }
    }
}

最后的最后,再说一个优化的小点:

  1. 我们的for循环,遍历截止条件是遍历到9。
  2. 但是我们题目要求的结果集个数是k个。

换句话说就是,假设我们遍历到5的时候,就已经满足了题目要求,那么6就不应该继续遍历下去。因此我们可以根据k来缩短右边界。

原本代码:

for (int i = cur; i <= 9; i++)

优化后代码:

// path是当前集合元素个数, k - path.size()也就是还差几个元素满足k个数。
for (int i = curValue; i <= 9 - (k - path.size()) + 1; i++)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zong_0915

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值