arrange numbers
Given an integer n, arrange the numbers 1∼n in a row, there will be many ways to arrange them. Now, please output all the permutation methods in lexicographical order.
input format
A line containing an integer n.
output format
Output all permutation schemes in lexicographical order, each scheme occupying one line.
data range
1≤n≤7
Input sample:
3
Sample output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Solution
The code above implements a depth-first search algorithm to generate all permutations of a given length n. The dfs function takes an integer u as input, which represents the current position in the permutation being generated. The function first checks if u is equal to n. If so, it means that a complete permutation has been generated, and the function outputs the permutation to the console.
If u is less than n, the function enters a loop that iterates over all integers from 1 to n. For each integer i, the function checks if i has already been used in the permutation. This is done using a boolean array state, where state[i] is true if i has already been used, and false otherwise. If i has not been used, the function adds i to the current position u in the permutation, sets state[i] to true to mark i as used, and recursively calls dfs with u+1 as the input.
After the recursive call to dfs returns, the function backtracks by setting state[i] back to false and removing i from the current position u in the permutation. This allows the function to explore other possible permutations that start with a different integer.
The main function reads an integer n from standard input, and then calls dfs with u=0 to generate all permutations of length n. The output of the program is a list of all permutations of length n.
Overall, this code is a simple and elegant implementation of a depth-first search algorithm for generating permutations. However, it has a time complexity of O(n!), which means that it can become very slow for large values of n. To improve the performance of the algorithm, it may be possible to use a more efficient algorithm, such as Heap's algorithm or Johnson-Trotter algorithm, which have a lower time complexity.
#include <bits/stdc++.h>
using namespace std;
const int N = 10;
int n;
int path[N];
bool state[N];
void dfs(int u) {
if (u == n) {
for (int i = 0; i < n; i ++ ) cout << path[i] << ' ';
puts("");
}
for (int i = 1; i <= n; i ++ ) {
if (!state[i]) {
path[u] = i;
state[i] = true;
dfs(u + 1);
state[i] = false;
}
}
return;
}
int main() {
cin >> n;
dfs(0);
return 0;
}