当前位置:网站首页>Leetcode T39: 组合总和
Leetcode T39: 组合总和
2022-07-01 08:08:00 【范谦之】
题目描述
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
思路
很常规的dfs题,但是由于很久没打dfs代码了,记录一下。
代码
List<List<Integer>> res = new ArrayList<List<Integer>>();
int n, tar;
int[] nums;
// 当前选取的组合,选到了第几个数字,当前和
void dfs(List<Integer> lis, int cur, int s) {
if(cur == n) {
if(s == tar)
res.add(lis);
} else {
// for(int x: lis) System.out.print(x+"\t"); System.out.println("\t,"+cur+"-"+s);
//对于当前数字可选,可不选
// 选,看是否超过,剪枝
if(s + nums[cur] <= tar) {
List<Integer> tmp = new ArrayList<Integer>(lis);
tmp.add(nums[cur]);
dfs(tmp, cur, s + nums[cur]);
}
// 不选
if(true) {
List<Integer> tmp = new ArrayList<Integer>(lis);
dfs(tmp, cur+1, s);
}
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
nums = candidates;
n = candidates.length;
tar = target;
dfs(new ArrayList<Integer>(), 0, 0);
return res;
}
边栏推荐
- [getting started] extract non repeating integers
- How can beginners correctly understand Google's official suggested architectural principles (questions?)
- 防“活化”照片蒙混过关,数据宝“活体检测+人脸识别”让刷脸更安全
- 软键盘高度报错
- Aardio - Shadow Gradient Text
- Li Kou daily question - day 31 -202 Happy number
- 图扑软件通过 CMMI5 级认证!| 国际软件领域高权威高等级认证
- Provincial election + noi Part VI skills and ideas
- Latex table
- 力扣每日一题-第31天-1790.仅执行一次字符串交换能否使两个字符串相等
猜你喜欢
随机推荐
Anddroid text to speech TTS implementation
Array: question brushing record
SharePoint - how to quickly check whether SharePoint is standard or enterprise edition?
Aardio - Method of self constructed geticonhandle
IMDB practice of emotion classification (simplernn, LSTM, Gru)
Gru of RNN
栈实现计算器
Cmake I two ways to compile source files
Keithley 2100 software 𞓜 Keithley2400 test software ns SourceMeter
Principle and process of embossing
[getting started] intercepting strings
Li Kou daily question - day 31 -1502 Judge whether an arithmetic sequence can be formed
Adding color blocks to Seaborn clustermap matrix
Uni hot update
【刷题】字符统计【0】
Insufficient executors to build thread pool
On June 30, 2022, the record of provincial competition + national competition of Bluebridge
[untitled]
Connect timed out of database connection
uni 热更新


![[untitled]](/img/d9/5e97f2de256b9749131b5bf1437d24.png)





![[website architecture] solve 90% of distributed transactions in one move, and introduce the working principles and application scenarios of database transactions and distributed transactions](/img/2c/07d729d49b1d74553decac4588074e.png)
![[untitled]](/img/b9/6922875009c2d29224a26ed2a22b01.jpg)