【Leetcode】Combination Sum II
2015-11-28 15:54
337 查看
题目链接:https://leetcode.com/problems/combination-sum-ii/
题目:
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
A solution set is:
思路:
candidate set每个元素只允许选择一次。因为set中可能会有重复的元素导致solution set中可能会有重复解,比如sum=8,candidate set[1,1,7],就有两个[1,7]解。每个元素只选择一次,可以在Combination
Sum 中改为 dspCombination(sum, i+1);,为了解决重复解的问题,我们引入HashSet保存解,最后在将hashSet转为List返回就好了。
算法:
题目:
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,5and target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:
candidate set每个元素只允许选择一次。因为set中可能会有重复的元素导致solution set中可能会有重复解,比如sum=8,candidate set[1,1,7],就有两个[1,7]解。每个元素只选择一次,可以在Combination
Sum 中改为 dspCombination(sum, i+1);,为了解决重复解的问题,我们引入HashSet保存解,最后在将hashSet转为List返回就好了。
算法:
int cl[] = null; List<List<Integer>> iLists = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); HashSet<ArrayList<Integer>> sets = new HashSet<ArrayList<Integer>>(); int target = 0; public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); this.cl = candidates; this.target = target; dspCombination2(0, 0); iLists.addAll(sets); //HashSet 转为 List return iLists; } private void dspCombination2(int sum, int level) { if (sum == target) { sets.add(new ArrayList<Integer>(list)); //用HashSet保存解 return; } else if (sum > target) { return; } else { for (int i = level; i < cl.length; i++) { sum += cl[i]; list.add(cl[i]); dspCombination2(sum, i + 1); //每个元素只允许选择一次 list.remove(list.size() - 1); sum -= cl[i]; } } }
相关文章推荐
- Java heap space
- shuoj1900 小6爱夜跑
- 浅谈C++多态性 http://blog.csdn.net/hackbuteer1/article/details/7475622
- 单例类的使用方法
- 初步了解JPA
- java 中常见异常
- 1-3-13:反向输出一个三位数
- 什么是单态模式
- —————————————1005————找规律的思想值得学习。
- UIWebview 适配 计算webview高度
- leetcode-dungeon-game
- 41.Android aapt工具
- asp.net实现输出xml的方法
- 选择图片
- java加载文件路径问题
- Spring声明式事务管理(基于注解的方式)
- angular实现两个select选择框互相传值
- HTML文本去除标签
- 正则表达式
- Remove Duplicates from Sorted List