Combination Sum - Leetcode
2015-02-17 06:06
295 查看
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<>(); List<Integer> path = new ArrayList<>(); Arrays.sort(candidates); DFS(result, path, candidates, target, 0); return result; } private void DFS(List<List<Integer>> result, List<Integer> path, int[] pool, int gap, int start){ if(gap == 0){ result.add(new ArrayList<>(path)); return; } for(int i=start; i<pool.length; i++){ if(gap < pool[i]) return; path.add(pool[i]); DFS(result, path, pool, gap-pool[i], i); path.remove(path.size()-1); } } }
思路: 大概的思路就是从第一个元素开始遍历,与target进行比较,如果gap为0,则说明找到解;否则(gap不为0)再从第一个元素开始验证求解。
分析:每一个元素都做的深度挖掘和验证, DFS
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.
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
2,3,6,7and target
7,
A solution set is:
[7]
[2, 2, 3]
相关文章推荐
- leetcode Combination Sum
- 【Leetcode】Combination Sum
- LeetCode(39) Combination Sum
- Combination Sum | && || Leetcode
- LeetCode--Combination Sum
- LeetCode-Combination Sum
- [C++]LeetCode: 33 Combination Sum
- 【Leetcode】Combination sum 1,2
- LeetCode 39: Combination Sum
- [leetcode javascript解题]Combination Sum
- [leetcode]Combination Sum
- LeetCode_Combination Sum
- [leetcode] Combination Sum
- LeetCode 039 Combination Sum
- LeetCode Online Judge 题目C# 练习 - Combination Sum
- [LeetCode] Combination Sum
- 算法。递归。之一: combination sum, leetcode
- LeetCode-- Combination Sum
- [Leetcode] Combination Sum
- leetcode--Combination Sum