美文网首页
对数组进行全排列

对数组进行全排列

作者: lxr_ | 来源:发表于2022-04-22 13:14 被阅读0次

    如对数组{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;
    }
    

    相关文章

      网友评论

          本文标题:对数组进行全排列

          本文链接:https://www.haomeiwen.com/subject/eyqnertx.html