本文主要是介绍LeetCode OJ:Combinations,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4], ]
递归:
class Solution {
public:void dfs(int d,int s,int k,int n,vector<int> &t,vector<vector<int>> &result){if(d==k){result.push_back(t);return;}for(int i=s+1;i<=n;i++){t.push_back(i);dfs(d+1,i,k,n,t,result);t.pop_back();}}vector<vector<int> > combine(int n, int k) {vector<vector<int>> result;vector<int> t;dfs(0,0,k,n,t,result);return result;}
};
迭代:
class Solution {
public: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>> result;do{vector<int> one(k);for(int i=0,index=0;i<n;++i)if(select[i])one[index++]=values[i];result.push_back(one);}while(prev_permutation(select.begin(),select.end()));return result;}
};
这篇关于LeetCode OJ:Combinations的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!