HZOJ#237. Recursive implementation of permutation enumeration

 

topic description

​ Arrange the n integers from 1−n in a row and shuffle the order, and output all possible options in lexicographical order.


enter

​ Enter an integer n. (1≤n≤8)

output

​ One set of schemes per line, and two numbers in each set of schemes are separated by spaces.

Note that there is no space after the last number on each line.

sample input

3

sample output

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
#include <iostream>  // 输入输出流
#include <cstdio>     // 标准输入输出库
#include <cstdlib>    // 标准库函数,包含通用工具函数
#include <queue>      // 队列容器
#include <stack>      // 栈容器
#include <algorithm>  // 算法库,包含各种算法函数
#include <string>     // 字符串库
#include <map>        // 映射容器
#include <set>        // 集合容器
#include <vector>     // 动态数组容器
using namespace std;

int arr[10], vis[10] = {0};  // 定义一个数组arr用于存放排列,vis数组用于标记数字是否被使用过

// 打印一个排列结果
void print_one_result(int n) {
    for (int i = 0; i < n; i++) {
        if (i) cout << " ";  // 输出空格分隔数字
        cout << arr[i];      // 输出当前位置的数字
    }
    cout << endl;
    return ;
}

// 递归生成全排列
void f(int i, int n) {
    if (i == n) {            // 当已经填满所有位置
        print_one_result(n);  // 打印这个排列
        return ;
    }
    for (int k = 1; k <= n; k++) {
        if (vis[k]) continue;  // 如果数字k已经被使用,跳过
        arr[i] = k;            // 将数字k放入当前位置
        vis[k] = 1;            // 标记数字k已被使用
        f(i + 1, n);           // 递归生成下一个位置的数字
        vis[k] = 0;            // 恢复数字k的未使用状态,以便后续排列生成
    }
    return ;
}

int main() {
    int n;
    cin >> n;     // 输入n,表示生成1到n的全排列
    f(0, n);      // 调用排列生成函数
    return 0;     // 返回0表示程序正常结束
}

The purpose of this code is to generate all full permutations from 1 to n. Full permutation refers to the total number of different permutations in which n elements (that is, all elements) are taken out of n different elements and arranged. Here, the backtracking algorithm is used to generate the full permutation. A backtracking algorithm is an algorithm that finds all solutions by exploring all possible candidate solutions. If the candidate solution is confirmed not to be a solution (or at least not the last one), the backtracking algorithm discards the solution by making some changes in the previous step.

Guess you like

Origin blog.csdn.net/dsafefvf/article/details/132675746