0039. Combination Sum (M)
Combination Sum (M)
题目
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
题意
给一串数,找出所有和等于目标值的组合,每个数字可以重复使用。
思路
排列组合题很容易想到使用回溯法,但与37. Sudoku Solver不同的是,37只要求在回溯中找到一种符合条件的解即可,而本题需要找到所有符合条件的解,因此这两种回溯法递归函数返回值的含义不同(实际上本题递归函数可以没有返回值,但加上返回值可以在适当的地方直接跳出循环,提高算法的效率)。
回溯法实现:
- 先对数组排序,方便处理。
- 递归边界为 sum >= target,其中当 sum == target 时,需要将该解记录下来。
- 递归主体:每次加入的值不小于上一次加入的值(因为是递增数列所以很容易处理), 加入后进行递归,递归完成后将加入的数去掉。如果递归返回值为false,说明刚刚加入的数已经使整个序列的和达到了最大限值,不用再继续加入更大的值,可以直接跳出。
代码实现
Java
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> ans = new ArrayList<>();
solve(candidates, target, 0, new ArrayList<>(), ans, 0);
return ans;
}
private boolean solve(int[] candidates, int target, int sum, List<Integer> list, List<List<Integer>> ans, int index) {
if (sum > target) {
return false;
}
if (sum == target) {
ans.add(new ArrayList<>(list));
return false;
}
for (int i = index; i < candidates.length; i++) {
list.add(candidates[i]);
boolean flag = solve(candidates, target, sum + candidates[i], list, ans, i);
list.remove(list.size() - 1);
if (!flag) {
break;
}
}
return true;
}
}
JavaScript
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function (candidates, target) {
let res = []
dfs(candidates, 0, 0, target, [], res)
return res
}
let dfs = function (candidates, index, sum, target, list, res) {
if (index === candidates.length || sum > target) {
return
}
if (sum === target) {
res.push([...list])
return
}
list.push(candidates[index])
dfs(candidates, index, sum + candidates[index], target, list, res)
list.pop()
dfs(candidates, index + 1, sum, target, list, res)
}
分类:
LeetCode
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~