1. 程式人生 > 其它 >c++實現全排列的三種方式

c++實現全排列的三種方式

遞迴方式

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int MAXN = 10;

bool visit[MAXN];//判斷某個元素是否被訪問過
char sequence[MAXN];//存放找到的全排列

void GetPermutation(string str, int index){
    // 找到結果並列印
    if (index == str.size()) {
        // 列印結果
        for (int i = 0; i < str.size(); ++i) {
            putchar(sequence[i]);
        }
        printf("\n");
    }
    for (int i = 0; i < str.size(); ++i) {
        if (visit[i]) {//被訪問過就跳過
            continue;
        } else {
            visit[i] = true;
            sequence[index] = str[i];
            //接著查詢下一位
            GetPermutation(str, index + 1);
            visit[i] = false;
        }
    }
}
int main(){
    string str;
    while (cin >> str) {
        sort(str.begin(), str.end());// 輸入的字串排序,保證以字典序輸出
        GetPermutation(str, 0);
        printf("\n");
    }
    return 0;
}

非遞迴方式

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

//非遞迴方式
//依次給出該排列的下一個排列
bool GetNextPermutation(string &str){
    int n = str.size();
    int index = n - 2;// 指向倒數第二個字元的下標
    //如果當前字元比後面的字元大就前移
    while (index >= 0 && str[index] >= str[index + 1]) {
        index--;
    }
    // 已經是字典序最大了
    if (index < 0) {
        return false;
    }
    for (int i = n - 1; i > index; --i) {
        // 找到第一個大於index的字元,然後交換
        if (str[i] > str[index]) {
            swap(str[index], str[i]);
            break;
        }
    }
    reverse(str.begin() + index + 1, str.end());
    return true;
}
int main(){
    string str;
    while (cin >> str) {
        sort(str.begin(), str.end());
        do {
            cout << str << endl;
        } while (GetNextPermutation(str));
        cout << endl;
    }

    return 0;
}

使用系統函式

next_permutation()和非遞迴方式求全排列的用法一樣,是計算當前序列的下一個序列,該函式位於algorithm標頭檔案中。

它有三個引數:

  • 序列的首地址
  • 序列的尾地址
  • 比較函式(可選),預設是字典序排列
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main(){
    string str;
    while (cin >> str) {
        sort(str.begin(), str.end());
        do {
            cout << str << endl;
        } while (next_permutation(str.begin(), str.end()));
        cout << endl;
    }

    return 0;
}