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.
Ensure that numbers within the set are sorted in ascending order.
Solution:
这种DFS有两种写法,这里进行总结。
写法一:
每层的递归是根据当前这个数字是否添加进行。所以最后终止条件有两个
1.递归到10
2.当前的ArrayList中包含的数字正好有k个
复杂度为2^10
写法二:
每层的递归是根据第i个选取的数字是多少。递归地终止条件只要一个,就是加入ArrayList的数字有k个。
复杂度为2^k
写法一代码:
import java.util.*;
public class Solution {
int n, k;
List<List<Integer>> list = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum3(int k, int n) {
this.k = k;
this.n = n;
dfs(1, 0, new ArrayList<Integer>());
return list;
}
void dfs(int num, int tempSum, ArrayList<Integer> array) {
if (num == 10) {
if (tempSum == n && array.size() == k)
list.add(new ArrayList<Integer>(array));
return;
}
dfs(num + 1, tempSum, array);
if (tempSum + num <= n) {
array.add(num);
dfs(num + 1, tempSum + num, array);
array.remove(array.size() - 1);
}
}
}
写法二代码:
很明显写法二比较适合这道题目,需要注意的就是每一层,选取第selectedNum+1个元素的时候,元素的范围不是无限制的,需要小于等于 10 - ( k - selectedNum);如果直接是小于10也可以,那就需要递归的时候判断一下,num<10的条件是否成立,否则num会等于10
import java.util.*;
public class Solution {
int n, k;
List<List<Integer>> list = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum3(int k, int n) {
this.k = k;
this.n = n;
dfs(1, 0, 0, new ArrayList<Integer>());
return list;
}
void dfs(int num, int selectedNum, int tempSum, ArrayList<Integer> array) {
if (selectedNum == k) {
if (tempSum == n)
list.add(new ArrayList<Integer>(array));
return;
}
for (int i = num; i <= 10 - (k - selectedNum); i++)
if (tempSum + i <= n) {
array.add(i);
dfs(i + 1, selectedNum + 1, tempSum + i, array);
array.remove(array.size() - 1);
}
}
}