文章目录
- [216. 组合总和 III](#216. 组合总和 III
)
216. 组合总和 III
思路:
定义一个 combinationSum3 方法,接受两个参数:k 表示组合中的数字个数,n 表示目标和。
在 combinationSum3 方法中,初始化一个空列表 ans 用于存储结果,以及一个空列表 path 用于暂时存储当前的组合。
调用深度优先搜索(DFS)算法 dfs,从数字 1 开始搜索可能的组合。
在 dfs 方法中,首先检查当前和 s 是否为 0,如果是则说明找到了一个符合条件的组合,判断当前组合中数字个数是否等于 k,如果是则将其添加到结果列表中。
然后进行递归搜索,遍历从 i+1 到 9 的所有可能数字,并更新当前和和组合路径。
递归结束后,需要将路径中最后一个数字移除,回溯到上一个状态,继续搜索其他可能的组合。
最后返回结果列表 ans。
java
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(1,n,ans,path,k);
return ans;
}
public void dfs(int i, int s, List<List<Integer>> ans, List<Integer> path, int k) {
if (s == 0) {
if (path.size() == k) {
ans.add(new ArrayList<>(path));
}
return;
}
if (i > 9 || i > s || path.size() >= k) {
return;
}
path.add(i);
dfs(i+1,s-i,ans,path,k);
path.remove(path.size()-1);
dfs(i+1,s,ans,path,k);
}
}
