题目
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.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
Example 1:
Input: k = 3, n = 7Output: [[1,2,4]]
Example 2:
Input: k = 3, n = 9Output: [[1,2,6], [1,3,5], [2,3,4]]
题意
从1-9这9个数中选取k个数,使其之和正好为n,求出所有这样的组合。
思路
排列组合题,使用回溯法很容易求解。
代码实现
Java
class Solution {public List<List<Integer>> combinationSum3(int k, int n) {List<List<Integer>> ans = new ArrayList<>();dfs(n, k, 0, 1, new ArrayList<>(), ans);return ans;}private void dfs(int n, int k, int sum, int start, List<Integer> temp, List<List<Integer>> ans) {if (temp.size() == k && sum == n) {ans.add(new ArrayList<>(temp));return;}if (temp.size() >= k || sum >= n) {return;}for (int i = start; i <= 9; i++) {temp.add(i);dfs(n, k, sum + i, i + 1, temp, ans);temp.remove(temp.size() - 1);}}}
JavaScript
/*** @param {number} k* @param {number} n* @return {number[][]}*/var combinationSum3 = function (k, n) {let ans = []dfs(0, [], 1, ans, k, n)return ans}let dfs = function (sum, tmp, begin, ans, k, n) {if (tmp.length === k && sum === n) {return ans.push([...tmp])}if (tmp.length >= k || sum >= n) {return}for (let i = begin; i <= 9; i++) {tmp.push(i)dfs(sum + i, tmp, i + 1, ans, k, n)tmp.pop()}}
