The use method, principle and manual implementation of the next_permutation function in C++

next_permutation is a function provided by C++ STL, which is used to find the next lexicographic permutation of a sequence. The next_permutation function is included <algorithm>in . Its usage is as follows:

#include <algorithm>
using namespace std;

int main() {
    
    
    int a[] = {
    
    1, 2, 3};
    do {
    
    
        // 处理当前排列
    } while (next_permutation(a, a + 3));
    return 0;
}

Among them, next_permutation accepts two iterators as parameters, indicating the start position and end position of the sequence to be operated. It alters this sequence so that it becomes the next lexicographic permutation and returns a bool indicating whether the next permutation was successfully generated. When the sequence is already a lexicographically largest permutation, there is no next permutation and the function will return false.

The principle of next_permutation is actually not complicated. It is actually a standard full permutation algorithm. For the current permutation, a reverse order pair is found from right to left. The reverse order remains unchanged for the numbers on the left, and the numbers on the right are sorted in descending order, and then the next permutation is obtained.

The method of manually implementing next_permutation is as follows:

bool next_permutation(int* a, int n) {
    
    
    int i = n - 2;
    while (i >= 0 && a[i] >= a[i + 1]) {
    
    
        i--;
    }
    if (i < 0) {
    
    
        return false;
    }
    int j = n - 1;
    while (j >= 0 && a[i] >= a[j]) {
    
    
        j--;
    }
    swap(a[i], a[j]);
    reverse(a + i + 1, a + n);
    return true;
}

This implementation accepts an integer array a and the length n of the array as parameters, and modifies the a array so that it becomes the next lexicographical order. Returns false if it is already the largest permutation.

Guess you like

Origin blog.csdn.net/m0_51913750/article/details/130540032