栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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> combinationSum(int[] candidates, int target) {
		int len = candidates.length;
		List> res = new ArrayList<>();
		
		if (len == 0) {
			return res;
		}
		
		Arrays.sort(candidates);
		Deque path = new ArrayDeque<>();
		dfs(candidates, 0, len, target, path, res);
		return res;
	} 
	
	private void dfs(int[] candidates, int begin, int len, int target, Deque path, List> 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();
		}
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/764338.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号