LeetCode—*组合问题Combinations
2014-09-01 11:27
393 查看
Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
这道题目的思路是比较简单的
一个循环首先选取一个值,放在最前面,比他大的值选取后放置后面
下面是使用push_back和pop_back进行处理,出现错误:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
这道题目的思路是比较简单的
一个循环首先选取一个值,放在最前面,比他大的值选取后放置后面
class Solution { public: vector<vector<int>> rt; vector<int> rtTemp; vector<vector<int> > combine(int n, int k) { rt.clear(); rtTemp.resize(k); if(k > n) { return rt; } SubCombine(1,n,k,0); return rt; } void SubCombine(int start,int n,int k,int dep) { if(k == dep) { rt.push_back(rtTemp); return; } for(int i = start; i <= n; i++) { rtTemp[dep] = i; SubCombine(i+1,n,k,dep+1); } } };这里需要注意使用索引首先要对vector进行resize操作:
下面是使用push_back和pop_back进行处理,出现错误:
class Solution { public: vector<vector<int>> rt; vector<int> rtTemp; vector<vector<int> > combine(int n, int k) { rt.clear(); rtTemp.resize(k); if(k > n) { return rt; } SubCombine(1,n,k,0); return rt; } void SubCombine(int start,int n,int k,int dep) { if(k == dep) { rt.push_back(rtTemp); rtTemp.pop_back(); return; } for(int i = start; i <= n; i++) { rtTemp.push_back(i); SubCombine(i+1,n,k,dep+1); } } };
相关文章推荐
- Leetcode中的组合排列问题:Permutations,Combinations,Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number 经典组合问题
- 手机键盘上的排列组合问题 Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number 电话按键字符的组合@LeetCode
- [LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合
- Leetcode:Combinations 组合
- leetcode-Combinations 复习复习排列组合
- Combinations 组合 思维问题
- leetcode 题解 || Letter Combinations of a Phone Number 问题
- [LeetCode] Combinations 组合项
- Letter Combinations of a Phone Number(带for循环的DFS,组合问题,递归总结)
- [LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合
- leetcode——Letter Combinations of a Phone Number 手机按键字母组合(AC)
- Leetcode:Combinations 组合
- leetcode 题解 || Letter Combinations of a Phone Number 问题
- [LeetCode系列]组合和枚举问题
- leetcode:Letter Combinations of a Phone Number(手机号码的字母组合)
- 【LeetCode】Permutations && Combinations 排列组合
- LeetCode | Letter Combinations of a Phone Number(号码的字符串组合)
- 【LeetCode-面试算法经典-Java实现】【017-Letter Combinations of a Phone Number (电话号码上的单词组合)】