力扣216 组合总和III java实现

216.组合总和III

找出所有相加之和为 nk个数的组合,且满足下列条件:

  • 只使用数字1到9
  • 每个数字 最多使用一次

返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

示例 1:

复制代码
输入: k = 3, n = 7
输出: [[1,2,4]]
解释:
1 + 2 + 4 = 7
没有其他符合的组合了。

示例 2:

复制代码
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
没有其他符合的组合了。

示例 3:

复制代码
输入: k = 4, n = 1
输出: []
解释: 不存在有效的组合。
在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。

提示:

  • 2 <= k <= 9
  • 1 <= n <= 60

本题就是在1,2,3,4,5,6,7,8,9这个集合中找到和为n的k个数的组合,相对于力扣77题,无非就是多了一个限制,本题是要找到和为n的k个数的组合,而整个集合已经是固定的了1,...,9

java 复制代码
    public static void main(String[] args) {   // 测试用
        List<List<Integer>> list = combinationSum3(3, 7);
        for (List<Integer> integers : list) {
            System.out.println(integers);
        }
    }

    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        helper(k, n, new ArrayList<>(), res, 1, 0);
        return res;
    }

    public static void helper(int k, int n, List<Integer> temp, List<List<Integer>> res, int cur, int sum){
        if (temp.size() > k || sum > n){
            return;
        }

        for (int i = cur; i <= 9; i++) {
            sum = sum + i;
            temp.add(i);
            if (sum == n && temp.size() == k){
                res.add(new ArrayList<>(temp));
                sum = sum - i;
                temp.remove(temp.size() - 1);
                return;
            }
            if (sum > n){
                sum = sum - i;
                temp.remove(temp.size() - 1);
                return;
            }
            helper(k, n, temp, res, i + 1, sum);
            sum = sum - i;
            temp.remove(temp.size() - 1);
        }
        return;
    }

以上为记录分享用,代码较差请见谅

相关推荐
需要82610 分钟前
MySQL 索引 B+ 树与“查询为什么变慢了
java·spring boot·spring·spring cloud·tomcat
一 乐11 分钟前
二手交易平台|基于springboot + vue二手交易平台(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序
万年咸鱼16 分钟前
编译Java源程序
java
Wang's Blog30 分钟前
Java 项目实战: 外卖平台-删除分类的关联校验与自定义业务异常
java·服务器·项目开发
INGNIGHT34 分钟前
270 · 电话号码的字母组合II(Trie)
linux·算法
hai_android39 分钟前
Kotlin / Android 常用函数使用示例手册
android·java·kotlin
2401_839080541 小时前
C++常见八股
数据结构·c++·算法
MayBaymax1 小时前
MongoDB 索引与事务
java·数据库·mongodb
vx-程序开发1 小时前
【计算机毕设】django校园跑腿服务系统83141
java·数据库·vue.js·spring boot·spring·elasticsearch·django
青山是哪个青山1 小时前
LeetCode 188:买卖股票的最佳时机 IV
算法