您的位置:首页 > 其它

39. Combination Sum

2016-02-28 08:31 295 查看
Backtracking问题

public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
List<Integer> item = new ArrayList<Integer>();
helper(candidates, target, res, item, 0, 0);
return res;
}

private void helper(int[] candidates, int target, List<List<Integer>> res, List<Integer> item, int start, int curSum) {
if(start >= candidates.length || curSum > target) {
return;
}
if(curSum == target) {
if(!res.contains(item)) {
res.add(new ArrayList<Integer>(item));
}
return;
}
for(int i = start; i < candidates.length; i++){
item.add(candidates[i]);
helper(candidates, target, res, item, i, curSum + candidates[i]);
item.remove(item.size() - 1);
}
return;
}


时间复杂度是指数级的,exponential
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: