LeetCode-039-组合总和
组合总和
题目描述:给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:穷举法
类似构造一棵多叉树,最大深度为candidates数组的长度,然后获取所有可能的路径,最大路径是由根节点到叶子节点,判断所有的路径之和是否等于target,如果相等,则加到结果集中,最后需要判重,把重复的组合去掉,最后返回。
import java.util.*;
public class LeetCode_039 {
/**
* 穷举法
*
* @param candidates
* @param target
* @return
*/
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
// 结果集
List<List<Integer>> result = new ArrayList<>();
// 所有可能的组合情况
Queue<List<Integer>> allPossibleCombinations = new LinkedList<>();
// 初始化所有的情况
for (int candidate : candidates) {
List<Integer> onePossibleCombination = new ArrayList<>();
onePossibleCombination.add(candidate);
allPossibleCombinations.add(onePossibleCombination);
}
while (!allPossibleCombinations.isEmpty()) {
List<Integer> temp = allPossibleCombinations.poll();
int sum = 0;
for (Integer num : temp) {
sum += num;
}
if (sum == target) {
result.add(temp);
} else if (sum < target) {
for (int candidate : candidates) {
// List复制方法
List<Integer> toAdd = new ArrayList<>(Arrays.asList(new Integer[temp.size()]));
Collections.copy(toAdd, temp);
toAdd.add(candidate);
allPossibleCombinations.add(toAdd);
}
}
}
// 去重后的结果
List<List<Integer>> result1 = new ArrayList<>();
for (int i = 0; i < result.size(); i++) {
boolean isRepeated = false;
List<Integer> one = result.get(i);
Collections.sort(one);
for (int j = i + 1; j < result.size(); j++) {
List<Integer> two = result.get(j);
Collections.sort(two);
if (one.size() != two.size()) {
continue;
}
boolean equals = true;
for (int x = 0; x < one.size(); x++) {
if (!one.get(x).equals(two.get(x))) {
equals = false;
continue;
}
}
if (equals) {
isRepeated = true;
}
}
if (!isRepeated) {
result1.add(one);
}
}
return result1;
}
public static void main(String[] args) {
int[] candidates = new int[]{8, 10, 6, 3, 4, 12, 11, 5, 9};
for (List<Integer> integers : combinationSum(candidates, 28)) {
for (Integer integer : integers) {
System.out.print(integer + " ");
}
System.out.println();
}
}
}
【每日寄语】 不要急着让生活给予所有的答案,有时我们需要耐心的等待。相信过程,坦然前行,不负生活,生活也必不负你。
分类:
LeetCode-个人题解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了