216. Combination Sum III

来源:互联网 发布:孙子兵法华杉 知乎 编辑:程序博客网 时间:2024/05/22 03:27

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,2,4]]


Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


Seen this question in a real interview before?
public class Solution {    public List<List<Integer>> combinationSum3(int k, int n) {       List<List<Integer>> re = new ArrayList<List<Integer>>();helper(new ArrayList<Integer>(), re, 1, 1, k, 0, n);return re;     }    public void helper(List<Integer> data, List<List<Integer>> re, int level, int j, int k, int cur, int n) {if (level > k) {if (cur == n)re.add(data);return;}for (int i = j; i < 10 && (k - level + 1) * i <= n; ++i) {List<Integer> next = new ArrayList<>(data);next.add(i);helper(next, re, level + 1, i + 1, k, cur + i, n);}}}



原创粉丝点击