Combination Sum III
2016-04-29 15:35
288 查看
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:
解答:
1.我的方法,回溯
输出:
1 2 6
1 3 5
2 3 4
注:这里
combination(res,list,vec,i+1,k-1,n-list[i]);
和
combination(res,list,vec,begin+1,k-1,n-list[i]);
输出的答案是不一样的。
以 i+1 输出的是从i以后的遍历得到的结果,就如以上答案所示。若以begin+1传递,则是下次遍历也从begin开始。得到的答案为以下:
1 2 6
1 3 5
1 4 4
1 5 3
2 2 5
2 3 4
2 4 3
3 2 4
3 3 3
4 2 3
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.我的方法,回溯
// // main.cpp // Combination Sum III // // Created by zjl on 16/4/29. // Copyright © 2016年 zjl. All rights reserved. // #include <iostream> #include <vector> using namespace std; void combination(vector<vector<int>>& res,vector<int> list,vector<int>& vec,int begin,int k,int n){ if(k==0 && n==0){ res.push_back(vec); return; } for(int i = begin; i < list.size(); i++){ if(n >= list[i]){ vec.push_back(list[i]); combination(res,list,vec,i+1,k-1,n-list[i]); vec.pop_back(); }else return; } } vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> res; vector<int> vec; vector<int> list; int begin = 0; if(k >= n) return res; for(int i = 0; i < n; i++) list.push_back(i+1); combination(res,list,vec,begin,k,n); return res; } void print_vec(vector<vector<int>> v){ for(int i = 0; i < v.size(); i++){ for(int j = 0; j < v[i].size(); j++){ cout<<v[i][j]<<" "; } cout<<endl; } } int main(int argc, const char * argv[]) { int k = 3; int n = 9; vector<vector<int>>res = combinationSum3(k, n); print_vec(res); return 0; }
输出:
1 2 6
1 3 5
2 3 4
注:这里
combination(res,list,vec,i+1,k-1,n-list[i]);
和
combination(res,list,vec,begin+1,k-1,n-list[i]);
输出的答案是不一样的。
以 i+1 输出的是从i以后的遍历得到的结果,就如以上答案所示。若以begin+1传递,则是下次遍历也从begin开始。得到的答案为以下:
1 2 6
1 3 5
1 4 4
1 5 3
2 2 5
2 3 4
2 4 3
3 2 4
3 3 3
4 2 3
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性