排列数字
思路:dfs(深度搜索),每次搜索没有标记过的数字,直到全部搜索完毕,输出路径,回溯,取消标记。
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 100010; int n; int path[N]; int st[N]; void dfs(int u) { if(u == n) { for (int i = 0; i < n; i ++ ) cout<<path[i]<<" "; cout<<endl; } //遍历1~n for(int i = 1; i <= n; i++) { if(!st[i]) { path[u] = i; st[i] = true; dfs(u + 1); st[i] = false; } } } int main() { cin>>n; dfs(0); return 0; }
浙公网安备 33010602011771号