思想:
方法一:DFS
start标记本次深度的递归从哪个数开始;
cur标记到了第几层;
path记录递归路径;
c++ code:
class Solution {
public:
//Combinations : dfs
void dfs(int n,int k,int start,int cur,vector<int> &path,vector<vector<int>> &result) {
if(cur == k) {
result.push_back(path);
}
for(int i=start; i<=n; ++i) {
path.push_back(i);
dfs(n,k,i+1,cur+1,path,result);
path.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
vector<vector<int>> result;
vector<int> path;
dfs(n,k,1,0,path,result);
return result;
}
};
java code:
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
dfs(res, path, 1, n ,k);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> path, int start, int n, int k) {
if(k == 0) {
res.add(new ArrayList(path));
return;
}
for(int i = start; i <= n; ++i) {
path.add(i);
dfs(res, path, i + 1, n, k - 1);
path.remove(path.size() - 1);
}
}
}
方法二:迭代
iota模板函数:
template <class ForwardIterator, class T> void iota (ForwardIterator first, ForwardIterator last, T val);
Store increasing sequence
Assigns to every element in the range
[first,last)
successive values of
val, as if incremented with
++val
after each element is written.
The behavior of this function template is equivalent to:
| |
需要包含头文件#include <numeric>;
fill_n模板函数:
std::fill_n
Fill sequence with value
Assigns
val to the first
n elements of the sequence pointed by
first.
The behavior of this function template is equivalent to:
| |
需要包含头文件#include <algorithm>;
class Solution {
public:
//Combinations : iteration
vector<vector<int> > combine(int n, int k) {
vector<int> values(n);
iota(values.begin(),values.end(),1);
vector<bool> select(n,false);
fill_n(select.begin(), k, true);
vector<vector<int>> res;
do {
vector<int> one(k);
for(int i=0,index=0; i<n; i++) {
if(select[i]) {
one[index++] = values[i];
}
}
res.push_back(one);
}while(prev_permutation(select.begin(), select.end()));
return res;
}
};
or
注意next_permutation()和prev_permutation的区别:
bool数组的字典序是false<true;
因此如果使用prev_permutation(),刚开始就要到全排列的最后一种情况,即前面全是true,后面全是false;
如果使用next_permutation(),则相反,刚开始是全排列的第一种情况,即前面全是false,后面全是true。
class Solution {
public:
//Combinations : iteration
vector<vector<int> > combine(int n, int k) {
vector<int> values(n);
iota(values.begin(),values.end(),1);
vector<bool> select(n,true);
fill_n(select.begin(), k, false);
vector<vector<int>> res;
do {
vector<int> one(k);
for(int i=0,index=0; i<n; i++) {
if(select[i]==false) {
one[index++] = values[i];
}
}
res.push_back(one);
}while(next_permutation(select.begin(), select.end()));
return res;
}
};