[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的算法思路给出一个小结。

原文地址:https://www.cnblogs.com/huntfor/p/3841987.html