• Combination Sum III

Combination Sum III

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.
Example 1:
Input: k = 3, n = 7
Output:
1. [[1,2,4]]

Example 2:
Input: k = 3, n = 9
Output:
1. [[1,2,6], [1,3,5], [2,3,4]]

Solution:
1. public class Solution {
2. public List<List> combinationSum3(int k, int n) {
3. List<List> res = new ArrayList<List>();
4. helper(k, n, 1, new ArrayList(), res);
5. return res;
6. }
7. 8. private void helper(int k, int n, int index, List sol, List<List> res) {
9. if (n == 0 && k == sol.size()) {
10. res.add(new ArrayList(sol));
11. return;
12. }
13. 14. if (index > 9 || n < 0) {
15. return;
16. }
17. 18. for (int i = index; i <= 9; i++) {
19. sol.add(i);
20. helper(k, n - i, i + 1, sol, res);
21. sol.remove(sol.size() - 1);
22. }
23. }
24. }