|
一、排列
#include<iostream>
#include<vector>
using namespace std;
class Solution{
private:
int n;
vector<vector<int>> ans;
vector<int> vis;
public:
void dfs(vector<int> &nums,vector<int>&c){
if(c.size() == 3){
ans.push_back(c);
return;
}
for(int i = 0; i < n; i++){
if(!vis[i]){
c.push_back(nums[i]);
vis[i] = 1;
dfs(nums,c);
vis[i] = 0;
c.pop_back();
}
}
}
vector<vector<int>> Combination(vector<int> &nums){
n = nums.size();
vis = vector<int>(n,0);
vector<int> c;
dfs(nums,c);
return ans;
}
};
int main(){
vector<int> nums = {1,2,3,4,5};
vector<vector<int>> ans = Solution().Combination(nums);
for(auto v:ans){
for(int x:v)
cout<<x<<" ";
cout<<'\n';
}
return 0;
}
二、组合
#include<iostream>
#include<vector>
using namespace std;
class Solution{
private:
int n;
vector<vector<int>> ans;
public:
void dfs(vector<int> &nums,int sx,vector<int> &c){
if(c.size() == 3){
ans.push_back(c);
return;
}
for(int i = sx; i < n; i++){
c.push_back(nums[i]);
dfs(nums,i+1,c);
c.pop_back();
}
}
vector<vector<int>> Permutation(vector<int> &nums){
vector<int> c;
n = nums.size();
dfs(nums,0,c);
return ans;
}
};
int main(){
vector<int> nums = {1,2,3,4,5};
vector<vector<int>> ans = Solution().Permutation(nums);
for(auto v:ans){
for(int x:v)
cout<<x<<" ";
cout<<'\n';
}
return 0;
}
|
|