LeetCode216——组合总和III
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/combination-sum-iii/
题目描述:
知识点:回溯
思路:回溯算法寻找所有符合条件的组合
往组合里添加新值时,确保新值比原有组合中的所有值都要大,这样就可以避免使用重复元素。
时间复杂度和空间复杂度均是O(9 ^ k)。
JAVA代码:
public class Solution {
private List<List<Integer>> retListList = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
generateCombination(new ArrayList<>(), 0, k, n);
return retListList;
}
private void generateCombination(List<Integer> list, int sum, int k, int n) {
if (list.size() == k && sum == n) {
retListList.add(new ArrayList<>(list));
return;
}
if (list.size() > k || sum > n) {
return;
}
for (int i = 1; i <= 9; i++) {
if (list.isEmpty() || i > list.get(list.size() - 1)) {
list.add(i);
generateCombination(list, sum + i, k, n);
list.remove(list.size() - 1);
}
}
}
}
LeetCode解题报告: