【leetcode刷题笔记】Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
题解:类似八皇后问题。每次把candidates[i]加入到numbers列表中,然后递归的搜索target-candidates[i]的组成方法。
要注意的一点是,将candidates[i]加入到numbers列表后,i前面的元素就不能再往numbers里面加了,只能再加入i本身或者i后面的元素。所以在递归函数中要有一个参数start,表明只有start本身或者以后的元素可以加入numbers中。每当递归函数参数target等于0的时候,说明找到了一组答案在numbers中,把numbers加入到answer里面就可以了。
代码如下:
1 public class Solution { 2 private void combiDfs(int[] candidates,int target,List<List<Integer>> answer,List<Integer> numbers,int start){ 3 if(target == 0){ 4 answer.add(new ArrayList<Integer>(numbers)); 5 return; 6 } 7 for(int i = start;i < candidates.length;i++){ 8 if(candidates[i] > target) 9 break; 10 numbers.add(candidates[i]); 11 combiDfs(candidates, target-candidates[i], answer, numbers,i); 12 numbers.remove(numbers.size()-1); 13 } 14 } 15 public List<List<Integer>> combinationSum(int[] candidates, int target) { 16 List<List<Integer>> answer = new ArrayList<List<Integer>>(); 17 List<Integer> numbers = new ArrayList<Integer>(); 18 Arrays.sort(candidates); 19 combiDfs(candidates, target, answer, numbers,0); 20 21 return answer; 22 23 } 24 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了