算法题(174):全排列问题
审题:
本题需要我们找出1~n选n个数的全排列情况,并按照五个场宽的要求输出
思路:
方法一:dfs搜索其实我们本题的思路和上一题的思路是几乎一致的B3623 枚举排列(递归实现排列型枚举) - 洛谷
我们都是依次放入前面没放过的数据,唯一的区别在于最终的输出格式,题目要求场宽为5,所以我们不能再使用cout来输出,而是使用printf结合%5d来完成输出
解题:
#include<iostream> #include<vector> using namespace std; int n; vector<int> path; bool f[10]; void dfs() {if (path.size() == n){for (auto e : path) printf("%5d", e);cout << endl;return;}for (int i = 1; i <= n; i++){if (f[i] == true) continue;path.push_back(i);f[i] = true;dfs();path.pop_back();f[i] = false;} } int main() {cin >> n;dfs();return 0; }
P1706 全排列问题 - 洛谷