p39

LeetCode p39 Combination Sum 题解

1.题目:

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.
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]
]

题意:

给一个数组,和一个数k,从你这个数组中选取一些数(可以重复),是和为k。
输出所有的组合方式。

2.解题思路:

见代码,递归。
先把数组排序。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
List<Integer> list = new ArrayList<Integer>();
combinationSum(candidates, target, 0, ans, list);

return ans;
}

public void combinationSum(int[] candidates, int target, int start,
List<List<Integer>> ans, List<Integer> list) {

if (target == 0) {
ans.add(new ArrayList<Integer>(list));
// System.out.println(list);
return;
}

for (int i = start; i < candidates.length
&& target - candidates[i] >= 0; i++) {
list.add(candidates[i]);
combinationSum(candidates, target - candidates[i], i, ans, list);
list.remove(list.size() - 1);

}

}
}

4.一些总结: