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);
    }

}

点击移步博客主页,欢迎光临~

相关推荐
科研小白_1 天前
基于遗传算法优化BP神经网络(GA-BP)的数据时序预测
人工智能·算法·回归
Terry Cao 漕河泾1 天前
基于dtw算法的动作、动态识别
算法
Miraitowa_cheems1 天前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号1 天前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区1 天前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao9851 天前
BCH码编译码仿真与误码率性能分析
算法
小白不想白a1 天前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法
剪一朵云爱着1 天前
力扣2080. 区间内查询数字的频率
算法·leetcode
落日漫游1 天前
数据结构笔试核心考点
java·开发语言·算法
workflower1 天前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程