全组合:
1.不可重复
//全组合 不可重复
#include<iostream>
using namespace std;
int n,k;
int array[1001];
int buffer[1001];
void depth_first_search(int,int);
int main()
{
ios::sync_with_stdio(false);
cin >> n >> k;
for(int i = 1 ; i <= n ; ++i)
cin >> array[i];
depth_first_search(1,1);
return 0;
};
void depth_first_search(int start,int cur)
{
if(cur > k)
{
for(int p = 1 ; p <= k ; ++p)
cout << buffer[p] << " ";
cout << endl;
return;
};
for(int q = start ; q <= n ; ++q)
{
buffer[cur] = array[q];
depth_first_search(q+1,cur+1);
};
};
2.可重复
//全组合 可重复
#include<iostream>
using namespace std;
int n,k;
int array[1001];
int buffer[1001];
void depth_first_search(int,int);
int main()
{
ios::sync_with_stdio(false);
cin >> n >> k;
for(int i = 1 ; i <= n ; ++i)
cin >> array[i];
depth_first_search(1,1);
return 0;
};
void depth_first_search(int start,int cur)
{
if(cur > k)
{
for(int p = 1 ; p <= k ; ++p)
cout << buffer[p] << " ";
cout << endl;
return;
};
for(int q = start ; q <= n ; ++q)
{
buffer[cur] = array[q];
depth_first_search(1,cur+1);
};
};
全排列:
1.不可重复
#include<iostream>
#include<cstring>
using namespace std;
int n,k;
int array[1001];
int buffer[1001];
bool visited[1001];
void depth_first_search(int);
int main()
{
ios::sync_with_stdio(false);
memset(visited,0,sizeof visited);
cin >> n >> k;
for(int i = 1 ; i <= n ; ++i)
cin >> array[i];
depth_first_search(1);
return 0;
};
void depth_first_search(int depth)
{
if(depth > k)
{
for(int i = 1 ; i <= k ; ++i)
cout << buffer[i] << " ";
cout << endl;
return;
};
int last_number = -1;
for(int i = 1 ; i <= n ; ++i)
{
if(!visited[i] && array[i] != last_number)
{
visited[i] = true;
buffer[depth] = array[i];
last_number = array[i];
depth_first_search(depth+1);
visited[i] = false;
};
};
};
2.可重复
#include<iostream>
#include<cstring>
using namespace std;
int n,k;
int array[1001];
int buffer[1001];
bool visited[1001];
void depth_first_search(int);
int main()
{
ios::sync_with_stdio(false);
memset(visited,0,sizeof visited);
cin >> n >> k;
for(int i = 1 ; i <= n ; ++i)
cin >> array[i];
depth_first_search(1);
return 0;
};
void depth_first_search(int depth)
{
if(depth > k)
{
for(int i = 1 ; i <= k ; ++i)
cout << buffer[i] << " ";
cout << endl;
return;
};
for(int i = 1 ; i <= n ; ++i)
{
if(!visited[i])
{
visited[i] = true;
buffer[depth] = array[i];
depth_first_search(depth+1);
visited[i] = false;
};
};
};