对数组进行全排列

2022-04-22  本文已影响0人  lxr_

如对数组{1,2,3}进行全排列得到
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2

参考:https://www.bilibili.com/video/BV1dx411S7WR?spm_id_from=333.337.search-card.all.click

代码:

#include <iostream>

#include <vector>

using namespace std;

void swap(vector<unsigned long long>& nn, int i, int j)
{
    int temp = nn[i];
    nn[i] = nn[j];
    nn[j] = temp;
}
//对数组nn进行全排列
void perm(vector<unsigned long long>& nn, unsigned long long index, unsigned long long n)
{
    if (index == n)
    {
        for (int i = 0; i < n + 1; i++)
        {
            cout << nn[i] << " ";

        }
        cout << endl;
    }
    else
    {
        for (int i = index; i <= n; i++)
        {
            //step1:数组中其他元素与第一个元素交换
            swap(nn, i, index);

            perm(nn, index + 1, n);

            //step2:数组中其他元素与第一个元素复原交换
            swap(nn, i, index);
        }
    }


}

int main(int argc, char** argv)
{

    vector<unsigned long long> nn;
    nn.push_back(1);
    nn.push_back(2);
    nn.push_back(3);
    perm(nn, 0, 2);

    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读