首页 > 代码库 > [leetcode]Combination Sum
[leetcode]Combination Sum
Combination Sum
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,不过本题可以包括重复数字,需要与[leetcode]Combination SumII做出区别
代码如下:
1 public class Solution { 2 List<List<Integer>> result = new ArrayList<List<Integer>>(); 3 public List<List<Integer>> combinationSum(int[] candidates, int target) { 4 if(candidates == null || candidates.length == 0) return result; 5 Arrays.sort(candidates); 6 List<Integer> list = new ArrayList<Integer>(); 7 dfs(candidates,list,0,target); 8 return result; 9 }10 private void dfs(int[] candidates,List<Integer> list,int k ,int target){11 if(target == 0){12 List<Integer> copy = new ArrayList<Integer>(list);13 result.add(copy);14 return;15 }16 if(target < candidates[k])return;17 for(int i = k; i < candidates.length; i++){18 list.add(candidates[i]);19 dfs(candidates,list,i,target - candidates[i]);20 list.remove(list.size() - 1);21 }22 }23 }
DFS的习题在leetcode中比较多,会在整理完所有的DFS之后,对DFS的算法思路给出一个小结。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。