暴力法(蛮力法)全排列输出

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/82791019

1.使用STL的函数next_permutation(a, a+n)可以轻松生成全排列,操作过程如下:

#include <bits/stdc++.h>

using namespace std;

int a[] = {1, 2, 3, 4, 5, 6};

void print(int n)  
{
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}


int main()
{
    do
    {
        print(6);
        
    } while (next_permutation(a, a+6));
    
    return 0;
}

2.DFS暴力枚举

#include <bits/stdc++.h>

using namespace std;

int a[6];
int n;
bool vis[6];       //该元素是否使用

void print()
{
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}


void dfs(int val, int inx)     //参数的含义表示将val放到下标索引为inx的位置上
{
    a[inx] = val;

    if (inx == n-1) {
        print();
        return ;
    }

    for (int i = 1; i <= n; i++) {
        if (vis[i] == false) {
            vis[i] = true;
            dfs(i, inx+1);
            vis[i] = false;
        }
    }
}

int main()
{
    n = 6;
    memset(vis, false, sizeof(vis));
    for (int i = 1; i <= n; i++) {
        vis[i] = true;
        dfs(i, 0);
        vis[i] = false;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/82791019
今日推荐