枚举排列组合(dfs)
可重复的排列
#include<iostream> using namespace std; int n, m; int dis[15]; //展示数组 int a[15]; //存放m个数 void dfs(int cnt) //cnt表示现在是第几个数 { if (cnt == m) { for (int i = 0; i < m; i++) cout << dis[i] << " "; cout << endl; return; } for (int i = 0; i < n; i++) { dis[cnt] = a[i]; dfs(cnt + 1); } } int main() { cin >> n >> m; for (int i = 0; i < n; i++) cin >> a[i]; dfs(0); return 0; }
不可重复的排列
#include<iostream> #include<cstring> using namespace std; int n, m; int dis[15]; int a[15]; int book[15];//标记数组 对应a里的每个数 void dfs(int cnt) { if (cnt == m) { for (int i = 0; i < m; i++) cout << dis[i] << " "; cout << endl; return; } for (int i = 0; i < n; i++) { if (book[i] == 0) { dis[cnt] = a[i]; book[i] = 1; dfs(cnt + 1); book[i] = 0; } } } int main() { memset(book, 0, sizeof(book)); cin >> n >> m; for (int i = 0; i < n; i++) cin >> a[i]; dfs(0); return 0; }
枚举组合
#include<iostream> #include<cstring> using namespace std; int n, m; int dis[15]; int a[15]; void dfs(int d,int cnt) //d表示标记位置 { if (cnt == m) { for (int i = 0; i < m; i++) cout << dis[i] << " "; cout << endl; return; } for (int i = d; i < n; i++) { dis[cnt] = a[i]; dfs(i+1,cnt + 1); } } int main() { cin >> n >> m; for (int i = 0; i < n; i++) cin >> a[i]; dfs(0,0); return 0; }