leetcode-216. Combination Sum III

本文介绍了一种寻找所有可能组合的方法,这些组合由k个数构成并加总至n,仅使用1到9的数字且每组组合需唯一。通过两段代码示例展示了如何优化算法以提高执行效率。

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

216. Combination Sum III

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.


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]]

题解:

 推荐先看一下:

Combination Sum

 Combination Sum II

和前面几题不同的就是这次对于集合是固定的,是  [1,2,3,4,5,6,7,8,9]  ,要求的和为 n 的集合的大小必须为 k

所以对于固定的集合,正好可以用 for 循环里的 i 来代替,在想 结果list 中添加 templist 的时候要判断一下大小即可

我一开始直接用 for 对为考虑这些条件的结果进行筛选,去掉大小不为 k 的集合,虽然也ac了,但是只beat 3%。。。


未优化:

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        int[] nums = {1,2,3,4,5,6,7,8,9};
        List<List<Integer>> list = new ArrayList<>();   
        List<List<Integer>> solu = new ArrayList<>(); 
        backtrack(list, new ArrayList<>(), nums, n, 0);
        
        for(int i = 0;i < list.size();i++){
            if(list.get(i).size()==k){
                solu.add(list.get(i));
            }
        }
        return solu;  
    }
    private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){    
        if(remain < 0) return;    
        else if(remain == 0) list.add(new ArrayList<>(tempList));    
        else{   
            for(int i = start; i < 9; i++){    
                tempList.add(nums[i]);    
                backtrack(list, tempList, nums, remain - nums[i], i+1); // not i + 1 because we can reuse same elements    
                tempList.remove(tempList.size() - 1);    
            }    
        }    
    } 
}//3ms


优化过的,AC:

class Solution {
    
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new ArrayList<>();
        combination(ans, new ArrayList<Integer>(), k, 1, n);
        return ans;
    }

    private void combination(List<List<Integer>> ans, List<Integer> comb, int k,  int start, int n) {
        if (comb.size() == k && n == 0) {
            List<Integer> li = new ArrayList<Integer>(comb);
            ans.add(li);
            return;
        }
        for (int i = start; i <= 9; i++) {
            comb.add(i);
            combination(ans, comb, k, i+1, n-i);
            comb.remove(comb.size() - 1);
        }
    }
}//1ms



### LeetCode Top 100 Popular Problems LeetCode provides an extensive collection of algorithmic challenges designed to help developers prepare for technical interviews and enhance their problem-solving skills. The platform categorizes these problems based on popularity, difficulty level, and frequency asked during tech interviews. The following list represents a curated selection of the most frequently practiced 100 problems from LeetCode: #### Array & String Manipulation 1. Two Sum[^2] 2. Add Two Numbers (Linked List)[^2] 3. Longest Substring Without Repeating Characters #### Dynamic Programming 4. Climbing Stairs 5. Coin Change 6. House Robber #### Depth-First Search (DFS) / Breadth-First Search (BFS) 7. Binary Tree Level Order Traversal[^3] 8. Surrounded Regions 9. Number of Islands #### Backtracking 10. Combination Sum 11. Subsets 12. Permutations #### Greedy Algorithms 13. Jump Game 14. Gas Station 15. Task Scheduler #### Sliding Window Technique 16. Minimum Size Subarray Sum 17. Longest Repeating Character Replacement #### Bit Manipulation 18. Single Number[^1] 19. Maximum Product of Word Lengths 20. Reverse Bits This list continues up until reaching approximately 100 items covering various categories including but not limited to Trees, Graphs, Sorting, Searching, Math, Design Patterns, etc.. Each category contains multiple representative questions that cover fundamental concepts as well as advanced techniques required by leading technology companies when conducting software engineering candidate assessments. For those interested in improving logical thinking through gaming activities outside traditional study methods, certain types of video games have been shown beneficial effects similar to engaging directly within competitive coding platforms [^4]. --related questions-- 1. How does participating in online coding competitions benefit personal development? 2. What specific advantages do DFS/BFS algorithms offer compared to other traversal strategies? 3. Can you provide examples illustrating how bit manipulation improves performance efficiency? 4. In what ways might regular participation in programming contests influence job interview success rates? 5. Are there any notable differences between solving problems on paper versus implementing solutions programmatically?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值