您的位置:首页 > 其它

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,7
and target
7
,

A solution set is:

[7]


[2, 2, 3]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: