c++枚举permutation

自己手动实现的枚举

我们可能会遇到这样一类问题,就是需要我们将问题的所有可能的解全部枚举出来,一一去验证。比如我要枚举{1, 2, 3}的所有组合,并按照字典序打印出来。可以这样做

#include <bits/stdc++.h>
using namespace std;

// 枚举
void permutation(int n, int *A, int cur)
{
    if (cur == n)
    {
        for (int i = 0; i < n; ++i) {
            cout << A[i] << " ";
        }
        cout << endl;
    }
    else
    {
        for (int i = 1; i <= n; ++i) {
            int ok=1;
            for (int j = 0; j < cur; ++j) {
                if (A[j] == i) ok = 0;
            }
            if (ok)
            {
                A[cur] = i;
                permutation(n, A, cur+1);
            }
        }
    }
}
int main()
{
    int n = 3;
    int A[] = {1, 2, 3};
    permutation(3, A, 0);
    return 0;
}

在这里插入图片描述

调用c++标准库实现

#include <bits/stdc++.h>
using namespace std;

// 数组类型
void test1()
{
    int a[] = {1, 3, 2};
    sort(a, a+3);
    while(next_permutation(a, a+3)) //a+4表示对前4个元素进行全排序,a+m表示对前m个元素进行全排序
    {
        cout << a[0] << " " << a[1] << " " << a[2] << endl;
    }
}

// char类型
void test2()
{
    char a[] = {'a', 'b', 'c'};
    char *first = a;
    char *last = a+3;
    while(next_permutation(first, last))
    {
        cout << a[0] << " " << a[1] << " " << a[2] << endl;
    }
}

// string类型
void test3()
{
    string s = "abc";
    sort(s.begin(), s.end());
    while(next_permutation(s.begin(), s.end()))
    {
        cout << s << endl;
    }
}

int main()
{
    test1();
    test2();
    test3();
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40438165/article/details/83188090
今日推荐