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

本文共 1194 字,大约阅读时间需要 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]]

 

思路:

组合问题,递归,1-9 每个数字都分放入和不放入两种情况。得到满足条件的就压入答案。

class Solution {public:    vector
> combinationSum3(int k, int n) { vector
partans; vector
> ans; combination(1, k, n, partans, ans); return ans; } void combination(int curNum, int k, int sum, vector
&partans, vector
> &ans) { if(curNum > 10 || sum < 0 || k < 0) return; //注意这里是 > 10, 否则数字9的答案无法压入 if(sum == 0 && k == 0) { ans.push_back(partans); } else { partans.push_back(curNum); combination(curNum + 1, k - 1, sum - curNum, partans, ans); partans.pop_back(); combination(curNum + 1, k, sum, partans, ans); } }};

 

转载于:https://www.cnblogs.com/dplearning/p/4528598.html

你可能感兴趣的文章
百词斩-斩家秘籍
查看>>
php反射
查看>>
Mysql主从配置,实现读写分离
查看>>
ES6中的Symbol
查看>>
1.8小结
查看>>
浅谈C#关于AOP编程的学习总结
查看>>
无障碍阅读
查看>>
bzoj1494 生成树计数 (dp+矩阵快速幂)
查看>>
关于Java的Daemon线程的理解
查看>>
Android开发之WebService介绍
查看>>
多线程死锁发生情景之一:同步的嵌套
查看>>
RestFramework之解析器
查看>>
Redis安装异常解决办法
查看>>
Jsonp post 跨域方案
查看>>
python字典操作和内置方法
查看>>
【Windows】Windows Restart Manager 重启管理器
查看>>
vim切换编程语言_一步步将vim改造成C/C++开发环境(IDE) (转自:Figthing)
查看>>
cascade sqlite 数据库_SQLITE ON UPDATE操作
查看>>
python是动态数据类型语言_[Python basic]Python basic数据类型;强类型动态脚本语言,基础,基本...
查看>>
apache 代理 图片无法展示_Apache中间件漏洞详解
查看>>