LeetCode 040 Combination Sum II
来源:互联网 发布:js ajax请求跨域问题 编辑:程序博客网 时间:2024/06/05 17:06
题目描述
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:
[1, 7] [1, 2, 5] [2, 6] [1, 1, 6]
代码
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); } }
1 0
- LeetCode 040 Combination Sum II
- LeetCode 040 Combination Sum II
- [LeetCode]040-Combination Sum II
- leetcode 040 Combination Sum II
- LeetCode 040 Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- [LeetCode] Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- LeetCode: Combination Sum II
- leetcode Combination Sum II
- [LeetCode]Combination Sum II
- [leetcode] Combination Sum II
- LeetCode-Combination Sum II
- Java 回调函数
- maven知识点
- A星寻路算法介绍
- mac os x使用Git简易入门教程
- 最大似然估计(MLE)和最大后验概率(MAP)
- LeetCode 040 Combination Sum II
- 环境配置三:Xcode Version 6.4 gtest环境搭建
- Intent传递数据 (得到返回数据)
- fmt的时间格式的设置的
- LeetCode String to Integer (atoi)
- 神的规范:排序算法(四):快速排序
- ActionResult返回Json时的exception
- ImageView实现对图片的缩放和旋转
- 升级ios9后RSA加密SecItemAdd出问题的解决方法