【leetcode刷题笔记】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] 


题解:类似八皇后问题。每次把candidates[i]加入到numbers列表中,然后递归的搜索target-candidates[i]的组成方法。

要注意的一点是,将candidates[i]加入到numbers列表后,i前面的元素就不能再往numbers里面加了,只能再加入i本身或者i后面的元素。所以在递归函数中要有一个参数start,表明只有start本身或者以后的元素可以加入numbers中。每当递归函数参数target等于0的时候,说明找到了一组答案在numbers中,把numbers加入到answer里面就可以了。

代码如下:

 1 public class Solution {
 2     private void combiDfs(int[] candidates,int target,List<List<Integer>> answer,List<Integer> numbers,int start){
 3         if(target == 0){
 4             answer.add(new ArrayList<Integer>(numbers));
 5             return;
 6         }
 7         for(int i = start;i < candidates.length;i++){
 8             if(candidates[i] > target)
 9                 break;
10             numbers.add(candidates[i]);
11             combiDfs(candidates, target-candidates[i], answer, numbers,i);
12             numbers.remove(numbers.size()-1);
13         }
14     }
15     public List<List<Integer>> combinationSum(int[] candidates, int target) {
16         List<List<Integer>> answer = new ArrayList<List<Integer>>();
17         List<Integer> numbers = new ArrayList<Integer>();
18         Arrays.sort(candidates);
19         combiDfs(candidates, target, answer, numbers,0);
20         
21         return answer;
22         
23     }
24 }
原文地址:https://www.cnblogs.com/sunshineatnoon/p/3860487.html