Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การสร้างทุกการเรียงสับเปลี่ยนย้อนกลับของอาร์เรย์ด้วย STL ใน C++


ในส่วนนี้เราจะดูวิธีสร้างการเรียงสับเปลี่ยนย้อนกลับ (reverse permutations) ทั้งหมดโดยใช้ STL ใน C++ การเรียงสับเปลี่ยนไปข้างหน้าและย้อนกลับของตัวเลขบางตัว เช่น (1, 2, 3) จะเป็นแบบด้านล่าง −

Forward permutation

1, 2, 3
1, 3, 2
2, 1, 3
2, 3, 1
3, 1, 2
3, 2, 1

Reversed permutation

3, 2, 1
3, 1, 2
2, 3, 1
2, 1, 3
1, 3, 2
1, 2, 3

เราจะใช้ฟังก์ชัน previous_permutation() เพื่อได้ผลลัพธ์

อัลกอริทึม

getPermutation(arr, n)

Begin
    sort arr
    reverse the arr
    repeat
        print array elements
    until the previous permutation calculation is not completed
End

ตัวอย่าง

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

void disp(int arr[], int n) {
    for(int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

void getPermutation(int arr[], int n) {
    sort(arr, arr + n);
    reverse(arr, arr + n);
    cout << "Possible permutations: \n";
    do {
        disp(arr, n);
    } while(prev_permutation(arr, arr + n));
}

int main() {
    int arr[] = {11, 22, 33, 44};
    int n = sizeof(arr) / sizeof(arr[0]);
    getPermutation(arr, n);
}

ผลลัพธ์

Possible permutations:
44 33 22 11
44 33 11 22
44 22 33 11
44 22 11 33
44 11 33 22
44 11 22 33
33 44 22 11
33 44 11 22
33 22 44 11
33 22 11 44
33 11 44 22
33 11 22 44
22 44 33 11
22 44 11 33
22 33 44 11
22 33 11 44
22 11 44 33
22 11 33 44
11 44 33 22
11 44 22 33
11 33 44 22
11 33 22 44
11 22 44 33
11 22 33 44