Combination Sum
来源:互联网 发布:sql server清空数据库 编辑:程序博客网 时间:2024/06/05 08:27
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.
public class Solution { /** * @param candidates: A list of integers * @param target:An integer * @return: A list of lists of integers */ public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> results = new ArrayList<>(); List<Integer> result = new ArrayList<>(); Set<List<Integer>> hash = new HashSet<>(); if (candidates == null || candidates.length == 0) { return results; } Arrays.sort(candidates); dfsHelper(candidates, 0, target, 0, results,result, hash); return results; } //使用hashset去重 private void dfsHelper(int[] candidates, int sum, int target, int index, List<List<Integer>> results, List<Integer> result, Set<List<Integer>> hash) { if (index > candidates.length ) { return; } if (sum == target) { ArrayList<Integer> temp = new ArrayList(result); if (!hash.contains(temp)) { results.add(temp); hash.add(temp); } } for (int i = index; i < candidates.length; i++) { //由于是排序数组,如果sum + candidates已经超过target,则不用往下搜索 if (sum + candidates[i] > target) { break; } sum += candidates[i]; result.add(candidates[i]); dfsHelper(candidates, sum, target, i, results, result, hash); sum -= result.get(result.size() - 1); result.remove(result.size() - 1); } } }
0 0
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- Combination Sum
- 紫书章三习题5——UVA 227 Puzzle
- CUDA 编程 之 配置cache函数
- Intel TBB简介及在Windows7 VS2013上源码的编译过程
- HDU 6015 Skip the Class【BestCoder Round #92】map
- 201403第一届CCF第二题 窗口
- Combination Sum
- A2DP & AVRCP,蓝牙音频协议的兄弟组合(1)
- 算法相关——Java排序算法之选择排序(六)
- Ubuntu搭建开发openchannelssd的qemu的虚拟机
- Arrays.copyOf() 用法:
- leetcode 345. Reverse Vowels of a String [EASY]
- 常见的RuntimeException异常总结
- 面向对象—轮播图
- [LeetCode]475. Heaters