LeetCode刷题笔记:39.组合总和

该博客介绍了一种使用回溯法解决组合总和问题的方法,即找到数组中所有可能的组合使得它们的和等于目标值。通过深度优先搜索(DFS),从根节点开始创建分支并减去数组中的值,避免重复路径。示例代码展示了如何在Python中实现这个算法,对数组进行排序并从当前节点开始避免选择相同的元素,确保组合的唯一性。
摘要由CSDN通过智能技术生成

1. 问题描述

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

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

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

2. 解题思路

参考链接:

https://leetcode-cn.com/problems/combination-sum/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-m-2/

以 输入:candidates = [2, 3, 6, 7], target = 7 为例:
① 以 7 为根节点,创建分支的时候做减法
② 从每一个父亲节点开始减去 candidates 数组中的一个值,得到该节点的子节点
③ 当子节点的值为 0 或者负数的时候停止创建分支
④ 从根节点到节点 0 的路径的全集即为题目所求

针对重复路径产生的解决方法:
在搜索的时候就去重,即每一次搜索的时候设置下一轮搜索的起点 begin,从每一层的第二个节点开始,都不能再搜索同一层节点已经使用过的candidates里面的元素。

3. 代码实现

class Solution {
	public List<List<Integer>> combinationSum(int[] candidates, int target) {
		int len = candidates.length;
		List<List<Integer>> res = new ArrayList<>();
		
		if (len == 0) {
			return res;
		}
		
		Arrays.sort(candidates);
		Deque<Integer> path = new ArrayDeque<>();
		dfs(candidates, 0, len, target, path, res);
		return res;
	} 
	
	private void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path, List<List<Integer>> res) {
		// 递归出口:当进入更深层时,小于0的部分会被剪枝
		if (target == 0) {
			res.add(new ArrayList<>(path))return;
		}
		
		for (int i = begin; i < len; i++) {
			if (target - candidates[i] < 0) {
				break;
			}
			path.addlast(candidates[i]);
			dfs(candidates, i, len, target - candidates[i], path, res);
			path.removeLast();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值