1. 程式人生 > >c++列舉permutation

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;
}

在這裡插入圖片描述