leecode刷题 之 40 Combination SumII
2018-03-21 12:42
141 查看
题意:给定一个集合C,与一个数值target,找出所有满足和为target的集合。(且每次求和时,C中的元素不能够重复使用)
注意:1.集合中的所有元素都是正的
2.得出的集合不能够重复
例如: C = {10,1,2,7,6,1,5} target = 8
结果:
[
[1,7]
[2,6]
[1,2,5]
[1,1,6]
]
具体实现代码如下:
![](//img-blog.csdn.net/20180321123502639?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L2RpcmtzbWFsbGVy/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
与leecode刷题 之 39 Combination Sum相对,本题不允许元素无限使用。所以
注意:1.集合中的所有元素都是正的
2.得出的集合不能够重复
例如: C = {10,1,2,7,6,1,5} target = 8
结果:
[
[1,7]
[2,6]
[1,2,5]
[1,1,6]
]
具体实现代码如下:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class HelloWorld { //用于测试的主方法 public static void main(String[] args) { int[] arrays = {10,1,2,7,6,1,5}; int target = 8; getCombinationSum1(arrays, target); System.out.println(combinationSum1.toString()); } public static List<List<Integer>> combinationSum1 = new ArrayList<>(); public static void getCombinationSum1(int[] arrays, int target) { //步骤一 将数据排序 Arrays.sort(arrays); //递归求和 combinationSum(arrays, 0, 0, new ArrayList<Integer>(),target); } /** * 求和,使得和为target(arrays中元素可以重复使用) * * @param arrays 总的元素 * @param start 开始计算的位置 * @param sum 当前已有元素的和 * @param currentAdderForSum 当前和为sum是的元素元素组成 * @param target 目标的值 */ private static void combinationSum(int[] arrays, int start, int sum, ArrayList<Integer> currentAdderForSum, int target) { if (sum == target) { //当前的集合已经满足和为target的要求,则将数据存储一下 combinationSum1.add(new ArrayList<>(currentAdderForSum)); //注意这里一定要重新New集合 return; } for (int i = start; i < arrays.length; i++) { //如果集合中有重复元素则为了避免重复,跳过本次循环 if (i > start && arrays[i] == arrays[i - 1]) { continue; } if ((sum + arrays[i]) > target) { //因为这是一个经过排序之后的升序数组,再接下来遍历循环没有意义,因此退出循环 break; } currentAdderForSum.add(arrays[i]); //与《leecode刷题 之 39 Combination Sum》中不同,因为本题中 集合中元素不可以无限使用 combinationSum(arrays, i + 1, sum + arrays[i], currentAdderForSum, target); currentAdderForSum.remove(currentAdderForSum.size() - 1); } } }
运行结果如下:
与leecode刷题 之 39 Combination Sum相对,本题不允许元素无限使用。所以
//在进行递归调用的使用,传入i+1,leecode 39中传入的是i combinationSum(arrays, i + 1, sum + arrays[i], currentAdderForSum, target);
相关文章推荐
- [导入]Guru of the Week:#40 多态控制.
- JS:control the IE (40)
- Nokia Series 40 3rd Edition Feature Pack 1 对应的设备
- 在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连接可能会导致此失败。 (provider: 命名管道提供程序, error: 40 - 无法打开到 SQL Server 的连接)
- 微软文档标准惹怒40,000人
- 《福布斯》亚洲版2007年中国40富豪榜单
- Windows API一日一练(40)CreateRectRgn和CombineRgn函数
- 每天学一点flash(40) 制作走马灯四
- Windows API一日一练(40)CreateRectRgn和CombineRgn函数
- 人生40宝典
- Oracle函數31-40
- NetBeans 时事通讯(刊号 # 40 - Dec 22, 2008)
- Delphi 与 DirectX 之 DelphiX(40): TDIB.Rotate();
- 40 个轻量级 JavaScript 库
- 40 个轻量级 JavaScript 库 (下)
- 40 个轻量级 JavaScript 库 (下)
- 40 个轻量级 JavaScript 库 (下)
- 40 个轻量级 JavaScript 库 (上)
- 稳扎稳打Silverlight(40) - 3.0绑定之Element to Element Binding, RelativeSource
- GdiPlus[40]: 不该忽略的一些基础结构