leetcode 216. Combination Sum III(数字的和III)

本文探讨了一种算法问题,即找出所有可能的组合,这些组合由k个数字组成,且加起来等于给定的数字n。数字范围限定在1到9之间,每组组合中的数字必须唯一。文章详细介绍了使用深度优先搜索(DFS)策略来解决这个问题的方法,并提供了具体的代码实现。

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

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.

Note:

All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

给出整数k和n,找到从1到9中可以使和为n的k个数

思路:
DFS
使用过的数字压入栈,当栈中数字和为n且个数为k时即满足一组解,用完一个数字后出栈,再进入下一个数字,从左到右
当n为0且栈中已有k个数字时,证明不需要再加入新的数字且已满足一组解,将解保存到结果list中

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        
        Stack<Integer> st = new Stack<>();
        combination(1, st, k, n, result);
        
        return result;
    }
    
    void combination(int start, Stack<Integer> st, int k, int target, List<List<Integer>> result) {
        if(st.size() == k && target == 0) {
            result.add(new ArrayList<Integer>(st));
            return;
        }
        
        if(st.size() > k || target < 0) {
            return;
        }
        
        for(int i = start; i <= 9; i++) {
            st.push(i);
            combination(i+1, st, k, target-i, result);
            st.pop();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值