216. Combination Sum III -Medium

本文介绍了一种通过回溯算法解决寻找K个数字总和为n的所有可能组合的方法,其中数字范围限定在1到9之间,并且每个数字只能使用一次。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question

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.

找出K个数字总和为n的所有可能情况,给出的K个数字的大小在1-9之间,每个数字在一种情况中只能使用一次

Exameple

Input: k = 3, n = 7

Output: [[1,2,4]]


Input: k = 3, n = 9

Output: [[1,2,6], [1,3,5], [2,3,4]]

Solution

  • 回溯解。因为要列出所有情况,所以我们只要遍历所有可能性并且取出K个元素总和为n的情况即可。

    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res = new ArrayList<>();
            backtracking(1, k, n, res, new ArrayList<>());
            return res;
        }
    
        /**
         * 思路:遍历所有可能性并且取出K个元素总和为n的情况
         * @param start: 当前加入链表的元素索引
         * @param k:需要K个数
         * @param n:还需要达到的目标值
         * @param res:保存所有结果
         * @param temp:保存当前组合的链表
         */
        public void backtracking(int start, int k, int n, List<List<Integer>> res, List<Integer> temp){
            // 如果当前链表中的元素大于K个,直接返回
            if(k < temp.size()) return;
    
            // 如果K个元素的总和等于n,则添加到结果集并返回
            if(k == temp.size() && n == 0){
                // 拷贝一个链表,因为temp接下去还会被修改
                List<Integer> newTempList = new ArrayList<>(temp);
                res.add(newTempList);
                return;
            }
            // 回溯
            for(int i = start; i < 10; i++){
                temp.add(i);
                backtracking(i + 1, k,n - i, res, temp);
                // 每次使用后都清空使用过的元素
                temp.remove(temp.size() - 1);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值