Programming/Algorithm
순열과 조합
SNOWOO
2021. 9. 24. 12:40
728x90
순열
#include <vector>
#include <iostream>
using namespace std;
int arr[5] = {1,2,3,4,5};
bool check[5];
vector<int> number;
int n,m; //nPm
void dfs(int depth)
{
if(depth == m)
{
for(int i=0;i<number.size();i++)
{
cout << number[i] << ' ';
}
cout << endl;
return;
}
for(int i=0;i<n;i++)
{
if(check[i])continue;
check[i] = true;
number.push_back(arr[i]);
dfs(depth+1);
number.pop_back();
check[i] = false;
}
}
조합
#include <iostream>
#include <vector>
using namespace std;
int arr[5] = {1,2,3,4,5};
bool check[5];
int n,m;//nCm
void dfs(int depth, int idx)
{
if(depth == m)
{
for(int i=0;i<n;i++)
{
if(check[i])
{
cout << arr[i]<< ' ';
}
}
cout << endl;
return;
}
for(int i=idx;i<n;i++)
{
if(check[i])continue;
check[i] = true;
dfs(depth+1, i);
check[i] = false;
}
}
중복순열
#include <iostream>
using namespace std;
int arr[5] = {1,2,3,4,5};
int arr2[5];
int n,m;
void dfs(int depth)
{
if(depth == m)
{
for(int i=0;i<m;i++)
{
cout << arr2[i]<< ' ';
}
cout << endl;
return;
}
for(int i=0;i<n;i++)
{
arr2[depth] = arr[i];
dfs(depth+1);
}
}
중복조합
#include <iostream>
#include <vector>
using namespace std;
int n,m;
int arr[5] = {1,2,3,4,5};
vector<int> v(5,0);
void dfs(int idx, int depth)
{
if(depth == m)
{
for(int i=0;i<m;i++)
{
cout << v[i] << ' ';
}
cout << endl;
return;
}
for(int i=idx;i<n;i++)
{
v[depth] = arr[i];
dfs(i, depth+1);
}
}
LIST