题解:
一条路走到头,然后再回头
vis数组来标记已走过的点,a数组来存数字
1 #include <bits/stdc++.h> 2 using namespace std; 3 int n; 4 bool vis[20]; 5 int a[20]; 6 7 void dfs(int x) 8 { 9 if (x > n) 10 { 11 for (int i = 1; i < n; ++i) 12 cout << a[i] << " "; 13 cout << a[n] << " " << endl; 14 return; // 回溯 15 } 16 17 for (int i = 1; i <= n; ++i) 18 { 19 if (!vis[i]) 20 { 21 vis[i] = 1; 22 a[x] = i; 23 dfs(x + 1); 24 vis[i] = 0; 25 } 26 } 27 return; // 回溯 28 } 29 30 int main() 31 { 32 cin >> n; 33 dfs(1); 34 return 0; 35 }
以下为python代码:
1 n = int(input()) 2 vis = [False] * (n + 1) 3 a = [0] * (n + 1) 4 5 6 def dfs(x): 7 if x > n: 8 for i in range(1, n + 1): 9 print(a[i], end=' ') 10 print() 11 return 12 13 for i in range(1, n + 1): 14 if not vis[i]: 15 vis[i] = 1 16 a[x] = i 17 dfs(x + 1) 18 vis[i] = 0 19 20 21 dfs(1)
标签:11,排列,20,数字,int,dfs,vis,print From: https://www.cnblogs.com/nijigasaki14/p/17527368.html