Combinations [LeetCode]

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],
]

  Summary: recursive functions

 class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > combinations;
if(n == || k == || n < k)
return combinations;
if(k == ){
for(int i = ; i <= n; i ++) {
vector<int> com(, i);
combinations.push_back(com);
}
return combinations;
} if(k == n){
vector<int> com;
for(int i = ; i <= n; i ++) {
com.push_back(i);
}
combinations.push_back(com);
return combinations;
} if(k <= n / ){
for(int i = ; i <= n - k; i ++){
if(i == n - k){
vector<int> com;
for(int j = n - k + ; j <= n; j ++)
com.push_back(j);
combinations.push_back(com);
break;
} int pick_num = i + ;
vector<vector<int> > sub_com = combine(n - pick_num, k - );
for(auto item : sub_com) {
for(int j = ; j < item.size(); j ++){
item[j] += pick_num;
}
item.insert(item.begin(), pick_num);
combinations.push_back(item);
}
}
return combinations;
}else{
combinations = combine(n, n - k);
vector<vector<int> > counter_combinations;
for(auto item : combinations){
vector<int> com;
int j = ;
for(int i = ; i <= n ; i ++){
if(j < item.size() && item[j] == i)
j ++;
else
com.push_back(i);
}
counter_combinations.push_back(com);
}
return counter_combinations;
} }
};
上一篇:js数组练习


下一篇:form提供的两种数据传输方式 get和post method=”post“和method=”get”