leetCode(31):Combination Sum III 分类: leetCode 2015-07-07 10:23 163人阅读 评论(0) 收藏
2015-07-07 10:23
369 查看
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:
Example 2:
Input: k = 3, n = 9
Output:
基本思路:首先确定第一个数,然后在剩余的数列中去寻找其余的数,找到则满足;说到这,自然而然--》递归
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]]
基本思路:首先确定第一个数,然后在剩余的数列中去寻找其余的数,找到则满足;说到这,自然而然--》递归
void combinationSum(int k,int index,int n,vector<int>& tmp,vector< vector<int> >& vec) {//k个数据相加为n,数据范围是index~9,tmp用于临时存放数据,vec用于存放返回值 if(k==1) {//还有最后一个名额,如果找不到相符的数据,说明没有满足的情况,需要返回 for(int i=index;i<=9;++i) { if(i==n) { tmp[k-1]=i; vec.push_back(tmp); break; } } } else { for(int i=index;i<=9;++i) { tmp[k-1]=i;//反向存放数据,递归 combinationSum(k-1,i+1,n-i,tmp,vec); } } } vector< vector<int> > combinationSum3(int k, int n) { vector< vector<int> > vec; vector<int> tmp; for(int i=0;i<k;++i) {//初始化 tmp.push_back(0); } combinationSum(k,1,n,tmp,vec); for(int i=0;i<vec.size();++i) {//因为数据是反向存放的,所以还需要一次反转 reverse(vec[i].begin(),vec[i].end()); } return vec; }
相关文章推荐
- javascript笔记01:javascript入门介绍
- C++读取特定路径下文件目录及文件名称&&文件结构
- kubenetes環境搭建
- 【leetcode】Binary Tree Maximum Path Sum
- Hadoop
- [深入学习C#]完成异步委托的三种方式
- android 存储5种方式
- C#关于摄像头的使用
- chrome firefox 获取模拟微信浏览器
- 【后端】content type大全 from http://tool.oschina.net/commons
- Android5.0网络之ipv6
- H5页面中删除iPhone自带样式
- WEB前端面试题整理
- [SoapUI] context.expand 和 groovyUtils.getXmlHolder 有什么不一样
- Python连接PostgreSQL
- Jquery DataTable 回调函数说明及示例
- eclipse内存设置
- 自定义弹出框
- 使用POI转换word doc文件
- Python中的类变量和成员变量