资讯专栏INFORMATION COLUMN

leetcode216. Combination Sum III

awokezhou / 2485人阅读

摘要:题目要求输入和,找到所有个不同数字的组合,这些组合中数字的和为参考,解答这是一道典型的的题目,通过递归的方式记录尝试的节点,如果成功则加入结果集,如果失败则返回上一个尝试的节点进行下一种尝试。

题目要求
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]]

输入k和n,找到所有k个不同数字的组合,这些组合中数字的和为n

参考Combination Sum I ,Combination Sum II

解答

这是一道典型的backtracking的题目,通过递归的方式记录尝试的节点,如果成功则加入结果集,如果失败则返回上一个尝试的节点进行下一种尝试。

    public List> combinationSum3(int k, int n) {
        List> result = new ArrayList>();
        combinationSum3(k,n,1,result, new ArrayList());
        return result;
    }
    
    public void combinationSum3(int k, int n, int startNumber, List> result, List current){
        if(k==0 && n==0){ result.add(new ArrayList(current)); return;}
        if(k==0 || n<0) return;
        for(int i = startNumber ; i<=9 ; i++){
            if(i>n){
                break;
            }
            current.add(i);
            combinationSum3(k-1, n-i, i+1, result, current);
            current.remove(current.size()-1);
        }
    }


想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67448.html

相关文章

  • Leetcode 相似题只有题号不含代码。

    找出string里的单词。 186. Reverse Words in a String II, 434. Number of Segments in a String combination类型题 77. Combinations 39. Combination Sum 40. Combination Sum II 216. Combination Sum III 494. Target S...

    StonePanda 评论0 收藏0
  • [LeetCode] Combination Sum III | Combination Sum I

    摘要:此时,若也正好减小为,说明当前集合是正解,加入数组。两个无法得到正解的情况是在为,而不为时,当然已经无法得到正解,。在不为而却已经小于等于的情况下,此时仍要加入其它数以令为,而要加入的数都是到的正整数,所以已无法满足令为的条件,。 Combination Sum I & II: link Combination Sum III Problem Find all possible com...

    leiyi 评论0 收藏0
  • [LintCode/LeetCode] Combination Sum I & II

    摘要:和唯一的不同是组合中不能存在重复的元素,因此,在递归时将初始位即可。 Combination Sum I Problem Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T...

    ThreeWords 评论0 收藏0
  • [Leetcode] Combination Sum 组合数之和

    摘要:深度优先搜索复杂度时间空间递归栈空间思路因为我们可以任意组合任意多个数,看其和是否是目标数,而且还要返回所有可能的组合,所以我们必须遍历所有可能性才能求解。这题是非常基本且典型的深度优先搜索并返回路径的题。本质上是有限深度优先搜索。 Combination Sum I Given a set of candidate numbers (C) and a target number (...

    GitCafe 评论0 收藏0
  • leetcode40 combination sum 2

    摘要:参考思路和非常类似,只是这里需要增加进行重复处理的部分。题目要求题目中新添的要求包括数组中存在重复值,而且数组中每个值只可以使用一次。需要注意的是,既然数组中存在重复的值,就要注意可能会将重复的情况加入结果数组。 参考 思路和leetcode39 combination sum 非常类似,只是这里需要增加进行重复处理的部分。请参考我对leetcode39进行解答的这篇博客。 题目要求 ...

    Code4App 评论0 收藏0

发表评论

0条评论

awokezhou

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<