题目原址
https://leetcode.com/problems/combination-sum-iii/description/
题目描述
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.
Example1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Example2:
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
解题思路
该提使用dfs的方法解决就可以了,属于DFS的一个基础应用
AC代码
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<Integer> list = new ArrayList<Integer>();
List<List<Integer>> ret = new ArrayList<List<Integer>>();
re(ret, list, k, n, 0, 1);
return ret;
}
public void re(List<List<Integer>> ret, List<Integer> list, int k, int n, int sum, int level) {
if(sum == n && k == 0)
ret.add(new ArrayList(list));
else if(sum > n || k <= 0) return;
for(int i = level; i <= 9; i++) {
list.add(i);
re(ret, list, k - 1, n, sum + i, i + 1);
list.remove(list.size() - 1);
}
}
}