我必须进行一个排列生成,但不接触数组{3 23 2 1 4} C++中的数字2和23

0md85ypi  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(85)

我必须对数组中的所有元素进行排列生成,但不接触元素2和23。例如:数组为:3 23 2 1 4输出:
3 23 2 1 4
3 23 2 4 1
1 23 2 3 4
1 23 2 4 3
4 23 2 3 1
4 23 2 1 3
我不知道如何在不多次打印相同答案的情况下实现此任务

#include <iostream>
using namespace std;

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

void perm(int arr[], int n, int size)
{
    if (n == 1)
        printingArr(arr, size);
    else
        for (int j = n - 1; j >= 0; j--)
        {
            if (arr[j] != arr[n - 1] && arr[j] != 23 && arr[j] != 2 && arr[n - 1] != 23 && arr[n - 1] != 2)
                swap(arr[j], arr[n - 1]);
            perm(arr, n - 1, size);
            if (arr[j] != arr[n - 1] && arr[j] != 23 && arr[j] != 2 && arr[n - 1] != 23 && arr[n - 1] != 2)
                swap(arr[n - 1], arr[j]);
        }
}

int main()
{
    int arr[] = {3, 23, 2, 1, 4};
    int size = sizeof(arr) / sizeof(arr[0]);
    perm(arr, size, size);
    cout << endl;
    system("PAUSE");
    return 0;
}
tgabmvqs

tgabmvqs1#

  • Make a subarray of size - 2 elements.
  • Sort it.
  • Then use std::next_permutation on that subarray.
  • Print:
  • the subarray's first element,
  • followed by the original array's second and third elements,
  • and the rest of the subarray.

Demo(https://godbolt.org/z/8v5ezW688)

#include <algorithm>  // copy, next_permutation, sort
#include <fmt/ranges.h>
#include <span>
#include <vector>

void perm(int arr[], int size) {
    if (size <= 3) {
        fmt::print("{}\n", fmt::join(std::span(arr, arr + size), ", "));
        return;
    }
    std::vector<int> subarr(size - 2);
    subarr[0] = arr[0];
    std::copy(arr + 3, arr + size, std::next(std::begin(subarr)));
    std::ranges::sort(subarr);
    int arr_1{ arr[1] };
    int arr_2{ arr[2] };
    do {
        fmt::print("{}, {}, {}, {}\n",
            subarr[0],
            arr_1,
            arr_2,
            fmt::join(
                std::span(std::next(std::begin(subarr)), size - 3),
                ", "
            )
        );
    } while (std::next_permutation(std::begin(subarr), std::end(subarr)));
}

int main() {
    int arr[] = {3, 23, 2, 1, 4};
    perm(arr, std::ssize(arr));
}

// Outputs:
//
//   1, 23, 2, 3, 4
//   1, 23, 2, 4, 3
//   3, 23, 2, 1, 4
//   3, 23, 2, 4, 1
//   4, 23, 2, 1, 3
//   4, 23, 2, 3, 1

相关问题