Leetcode 216. Combination Sum III
The problem “216. Combination Sum III” from LeetCode requires you to find all possible combinations of k
numbers that add up to a number n
, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
k
and n
?
1 ≤ k ≤ 9
and 1 ≤ n ≤ 60
.We can use a backtracking approach to solve this problem:
n
.k
and the sum is n
, add it to the result list.Here’s the code implementing the above strategy:
import java.util.ArrayList;
import java.util.List;
public class CombinationSumIII {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), k, n, 1);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> combination, int k, int n, int start) {
if (combination.size() == k && n == 0) {
result.add(new ArrayList<>(combination));
return;
}
for (int i = start; i <= 9; i++) {
if (i > n) {
break;
}
combination.add(i);
backtrack(result, combination, k, n - i, i + 1);
combination.remove(combination.size() - 1);
}
}
public static void main(String[] args) {
CombinationSumIII cs3 = new CombinationSumIII();
System.out.println(cs3.combinationSum3(3, 7)); // Output: [[1, 2, 4]]
System.out.println(cs3.combinationSum3(3, 9)); // Output: [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
}
}
The time complexity of this solution involves exploring all the combinations of numbers from 1 to 9:
k
.C(9, k)
(combinations of 9 choose k) possibilities.9!/(k! * (9-k)!)
iterations.Therefore, the time complexity is approximately (O(2^n)), specifically considering the small constant limits (numbers 1 to 9) and combinations within bounds of 9.
The space complexity is mainly due to:
Hence, the space complexity is (O(k)) for the recursive call stack in the worst case, plus the space required to store valid combinations, which in the worst scenario is (O(C(9, k))).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?