216.组合总和III
找出所有相加之和为n的k个数的组合,且满足下列条件:
- 只使用数字1到9
- 每个数字最多使用一次
返回所有可能的有效组合的列表。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例 1:
输入:k= 3,n= 7输出:[[1,2,4]]解释:1 + 2 + 4 = 7 没有其他符合的组合了。
示例 2:
输入:k= 3,n= 9输出:[[1,2,6], [1,3,5], [2,3,4]]解释:1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 没有其他符合的组合了。
示例 3:
输入:k = 4, n = 1输出:[]解释:不存在有效的组合。 在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。
提示:
2 <= k <= 91 <= n <= 60
本题就是在[1,2,3,4,5,6,7,8,9]这个集合中找到和为n的k个数的组合,相对于力扣77题,无非就是多了一个限制,本题是要找到和为n的k个数的组合,而整个集合已经是固定的了[1,...,9]。
public static void main(String[] args) { // 测试用 List<List<Integer>> list = combinationSum3(3, 7); for (List<Integer> integers : list) { System.out.println(integers); } } public static List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> res = new ArrayList<>(); helper(k, n, new ArrayList<>(), res, 1, 0); return res; } public static void helper(int k, int n, List<Integer> temp, List<List<Integer>> res, int cur, int sum){ if (temp.size() > k || sum > n){ return; } for (int i = cur; i <= 9; i++) { sum = sum + i; temp.add(i); if (sum == n && temp.size() == k){ res.add(new ArrayList<>(temp)); sum = sum - i; temp.remove(temp.size() - 1); return; } if (sum > n){ sum = sum - i; temp.remove(temp.size() - 1); return; } helper(k, n, temp, res, i + 1, sum); sum = sum - i; temp.remove(temp.size() - 1); } return; }以上为记录分享用,代码较差请见谅