首页 > 学院 > 开发设计 > 正文

Combination Sum

2019-11-06 09:09:17
字体:
来源:转载
供稿:网友

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.

Notice

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.

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); } } }
上一篇:Combination Sum

下一篇:SQL数据库中的范式

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表