Open underwindfall opened 3 years ago
如果是按长度从小到大输出
public List<List<Integer>> combinationSumInOrder(int[] candidates, int target) {
int len = candidates.length;
List<List<Integer>> res = new ArrayList<>();
if (len == 0) {
return res;
}
Arrays.sort(candidates);
List<Integer> path = new ArrayList<>();
for (int n = 1; n <= target / candidates[0]; n++) {
dfs(candidates, 0, 0, n, target, path, res);
}
return res;
}
private void dfs(int[] candidates, int startIndex, int depth, int len, int target, List<Integer> path,
List<List<Integer>> res) {
if (target == 0 && depth == len) {
res.add(new ArrayList<>(path));
return;
}
// 剪枝操作在这里
for (int i = startIndex; i < candidates.length; i++) {
if (candidates[i] > target)
break;
path.add(candidates[i]);
dfs(candidates, i, depth + 1, len, target - candidates[i], path, res);
// backtracking
path.remove(path.size() - 1);
}
}
https://leetcode-cn.com/problems/combination-sum/
思路
[ ] 刷15mins
[ ] 刷5mins