深入了解next_permutation()

发布时间:2023-05-23

一、函数介绍

next_permutation()是C++ STL中的一个函数,其作用是将一个排列变成其下一个排列,如果当前排列为最后一个排列,则将其变成第一个排列。

bool next_permutation(first, last, cmp);

其中,firstlast是迭代器,即需要排序的区间;cmp是函数对象,用于比较元素的大小。

二、函数原理

我们以"123"进行举例,其全排列为"123", "132", "213", "231", "312", "321"。 next_permutation()首先从最后一个元素开始向前找,找到第一个降序的元素,即找到"2"。然后再从后往前找到第一个比这个数字大的数字,即找到"3"。然后将两个数字交换,得到"1332"。最后再将"2331"反转得到"2313"。

1 2 3 -> 1 3 2 -> 2 1 3 -> 2 3 1 -> 3 1 2 -> 3 2 1
         -> 1 2 3    -> 1 2 3   -> 1 2 3   -> 1 2 3

三、代码示例

下面是一个使用next_permutation()的示例代码,对数组进行全排列并输出。

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int arr[] = {1, 2, 3};
    sort(arr, arr+3);  // 需要先将数组排序
    do {
        for (int i = 0; i < 3; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    } while (next_permutation(arr, arr+3));
    return 0;
}

四、使用自定义比较函数

在上述示例中,使用了默认的less<int>作为函数对象进行比较。实际上,我们可以使用自定义的比较函数进行元素的排序。 比如我们想要按照方案的总和从小到大进行排序。

#include <iostream>
#include <algorithm>
using namespace std;
struct Plan {
    int id;
    int sum;
    bool operator < (const Plan& p) const {
        return sum < p.sum;
    }
} plans[] = {{1, 100}, {2, 120}, {3, 90}};
int main() {
    sort(plans, plans+3);
    do {
        for (int i = 0; i < 3; i++) {
            cout << plans[i].id << " ";
        }
        cout << endl;
    } while (next_permutation(plans, plans+3));
    return 0;
}

五、使用next_permutation()进行字符串的排列组合

除了数组的全排列,next_permutation()同样适用于字符串的排列组合。

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    string str = "abc";
    sort(str.begin(), str.end());
    do {
        cout << str << endl;
    } while (next_permutation(str.begin(), str.end()));
    return 0;
}

输出结果:

abc
acb
bac
bca
cab
cba

六、总结

本文主要介绍了next_permutation()函数的使用以及原理。通过使用该函数,可以很方便地对一个数组、字符串进行全排列、排列组合等操作。