5972
这是递归的入门题,求全排列,第一种方法用STL中的函数next_permutation,可以很容易的实现。首先建立好数组,将需要全排列的数字进行初始化,然后调用next_permutation(a,a+n),按照地址进行全排列打印结果.
#include <stdio.h> #include <algorithm> using namespace std; int a[20]; int main() { int n; scanf("%d", &n); int i; for (i = 0; i < n; i++) { a[i] = i + 1; } do { for (i = 0; i < n; i++) { if (i != n - 1) printf("%d ", a[i]); else printf("%d", a[i]); } printf("\n"); } while (next_permutation(a, a + n)); }
2.另外一种递归写法如下。
#include <bits/stdc++.h> using namespace std; vector<int>ans; bool hashTable[20] = { false };//true选false不选 int i; int n; void DFS(int index) { if (index == n) { for (i = 0; i < n; i++) { if (i != n - 1) printf("%d ", ans[i]); else printf("%d", ans[i]); } printf("\n"); return; } for (int x = 0; x < n; x++) { if (hashTable[x] == false) { ans.push_back(x+1);//选这个元素 hashTable[x] = true;//将他设置为已选择 DFS(index + 1);//不选这个元素 ans.pop_back();//弹出 hashTable[x] = false;//把这个元素设置为未选择 } } } int main() { scanf("%d", &n); DFS(0); }
5973
和这个题很像,求的是组合,也是DFS递归模板的另一版本.
#include <cstdio> #include <vector> using namespace std; int n, r; int a[30]; vector<int>ans; void DFS(int index, int v) { if (index == n) { if (v == r) { vector<int>::iterator it = ans.begin(); for (; it != ans.end(); it++) { if (it != ans.end() - 1) { printf("%d ", *it); } else printf("%d", *it); } printf("\n"); } return; } ans.push_back(a[index]); DFS(index + 1, v + 1); ans.pop_back(); DFS(index + 1, v); } int main() { scanf("%d %d", &n, &r); int i; for (i = 0; i < n; i++) { a[i] = i + 1; } DFS(0, 0); }