您的位置:首页 > 其它

leetcode -- Combination Sum

2013-08-03 17:26 281 查看
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]


本题是求解所有可能的组合数,可用DFS来求解,如需求解最优解,需使用DP

DFS的递归函数中只处理当前状态节点n,而不关心它的下一状态

public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = candidates.length;
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
if(len == 0)
return results;

Arrays.sort(candidates);

ArrayList<Integer> result = new ArrayList<Integer>();
int level = 0;
int sum = 0;
DFS(candidates, level, sum, target, result, results);
return results;
}

public void DFS(int[] candidates, int level, int sum, int target, ArrayList<Integer> result,
ArrayList<ArrayList<Integer>> results){
if(sum > target)
return;

if(sum == target){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.addAll(result);
results.add(tmp);
return;
}
if(sum < target){
for(int i = level; i < candidates.length; i++){
sum += candidates[i];
result.add(candidates[i]);
DFS(candidates, i, sum, target, result, results);
result.remove(result.size() - 1);
sum -= candidates[i];
}
}
}
}


ref:

DFS 算法入门:/article/4073746.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: