LeetCode 040 Combination Sum II
2015-11-10 10:30
495 查看
题目描述
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[code][1, 7] [1, 2, 5] [2, 6] [1, 1, 6]
代码
[code] Set<List<Integer>> result; ArrayList<Integer> cur; int[] candidates; int target; public List<List<Integer>> combinationSum2(int[] candidates, int target) { if (candidates == null || candidates.length == 0) { return new ArrayList<List<Integer>>(); } result = new HashSet<List<Integer>>(); cur = new ArrayList<Integer>(); this.candidates = candidates; this.target = target; Arrays.sort(candidates); dfs(0, target); return new ArrayList<List<Integer>>(result); } void dfs(int j, int target) { // 找到解,存到result中 if (target == 0) { result.add(new ArrayList<Integer>(cur)); return; } for (int i = j; i < candidates.length; i++) { // 如果小于就返回,表明此后不会有解了! if (candidates[i] > target) { return; } // 递归求解 cur.add(candidates[i]); dfs(i + 1, target - candidates[i]); cur.remove(cur.size() - 1); } }
相关文章推荐
- maven知识点
- MVC HtmlHelper用法大全
- tomcat的webapp下的root文件夹的作用是什么
- Android常见XML转义字符
- IOS开源项目Coding学习笔记(3):注册界面RegisterViewController
- 动态修改background之后padding失效
- 26种迹象你该考虑辞掉程序员的工作
- Ubuntu中设置环境变量的几种方式及区别
- Java数据库连接-JNDI方式- 配置Tomcat6.0 连接池 配置相关
- svn st 状态详解
- Jquery中图片瀑布流
- 完美解决VS2003.Net fatal error LNK1201: 写入程序数据库“.pdb”时出错我的开发环境是Win7旗舰64位+VS2003.Net,经常卡pdb错误,文末给出一个完美的解决
- while循环语句的使用
- Android 2.3 NFC简介
- 将Xml或Json生成类的最简单方式
- RAID详解[RAID0/RAID1/RAID10/RAID5]
- 排序算法之冒泡、插入和希尔排序
- JSPatch库, 一个Apple官方支持的实现在线更新iOS应用的库
- mongodb网络yum源
- jquery插件--ajaxfileupload.js上传文件原理分析