博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Combination Sum III -- leetcode
阅读量:7122 次
发布时间:2019-06-28

本文共 995 字,大约阅读时间需要 3 分钟。

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.

Ensure that numbers within the set are sorted in ascending order.

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

Credits:

基本思路:

使用dfs进行穷举遍历。

因为结果集要求按升序排列,则先选择较小的数字,然后从剩下的较大数中进行选择。

确保每次选择的数都大于上次选择的。

class Solution {public:    vector
> combinationSum3(int k, int n) { vector
> ans; vector
seq; helper(ans, seq, k, n); return ans; } void helper(vector
>& ans, vector
& seq, int k, int n) { if (!k && !n) return ans.push_back(seq); if (!k || n<0) return; int start = seq.empty() ? 1 : seq.back()+1; for (int i=start; i<=9; i++) { seq.push_back(i); helper(ans, seq, k-1, n-i); seq.pop_back(); } }};

转载地址:http://jdael.baihongyu.com/

你可能感兴趣的文章
七牛李倩:⼯程效率如何为研发赋能
查看>>
从“被动挖光缆”到“主动剪网线”,蚂蚁金服异地多活的微服务体系
查看>>
PhpStorm2016.3激活
查看>>
Docker4Dev #7 新瓶装老酒 – 使用 Windows Container运行ASP.NET MVC 2 + SQLExpress 应用
查看>>
使用vue.js构建一个知乎日报
查看>>
Microsoft Flow发布GA版本
查看>>
Python 赋值的一般含义是引用
查看>>
magento2 在香港用paypal
查看>>
Yii系列(1)打造虚拟开发环境及Yii的安装配置
查看>>
img/background/iconfont---谁最适合你?
查看>>
我的iOS程序生涯的起点
查看>>
程序员的工匠精神
查看>>
【underscore.js 源码解读】for ... in 存在的浏览器兼容问题你造吗
查看>>
Sass 与 Compass 实战经验总结
查看>>
微信公众号开发小记——3.接入三方登录
查看>>
个推获7亿元C轮募资,SDK接入超80亿
查看>>
如何10分钟让APP实现实时互动?
查看>>
Consul入门01 - 安装Consul
查看>>
Swift 编程思想,第一部分(补遗):牺牲小马
查看>>
css 不规整元素的宽高等比例
查看>>