请 斧正 感觉有点over kill
public List> findSum(int[] candidates, int k, int target) {
List> ret = new ArrayList>();
if (candidates.length == 0) return ret;
Arrays.sort(candidates);
List path = new ArrayList();
dfs(candidates, 0, k, target, path, ret);
return ret;
}
private void dfs(int[] candidates, int depth, int k, int target, List<
Integer> path, List> ret) {
if (k == path.size()) {
if (target == 0) ret.add(new ArrayList(path));
}
else {
if (target < 0 || depth == candidates.length || target <
candidates[depth]) {
return;
}
else {
for(int i = depth; i < candidates.length; ++i) {
path.add(i);
dfs(candidates, i, k, target - candidates[i], path, ret);
path.remove(path.size() - 1);
}
}
}
}
{-2, -1, 0, 0, 1, 1, 1, 2}
0 1 2 3 4 5 6 7
[0, 2, 7]
[0, 3, 7]
[0, 4, 4]
[0, 4, 5]
[0, 4, 6]
[0, 5, 5]
[0, 5, 6]
[0, 6, 6]
[1, 1, 7]
[1, 2, 4]
[1, 2, 5]
[1, 2, 6]
[1, 3, 4]
[1, 3, 5]
[1, 3, 6]
[2, 2, 2]
[2, 2, 3]
[2, 3, 3]
[3, 3, 3]
-2, 0, 1, 2, 4, 6
0 1 2 3 4 5
是说比如-2,4,6,1,2,0取三数和为0的话,那么
-2,-2,4
-2,2,0
-2,1,1
0,0,0
[0, 0, 4] -2, -2, 4
[0, 1, 3] -2, 0, 2
[0, 2, 2] -2, 1, 1
[1, 1, 1] 0, 0, 0