全排列(DFS)

题面(from luogu)
全排列问题
输出自然数1到n所有不重复的排列,即n的全排列,要求所产生的任一数字序列中不允许出现重复的数字。

输入格式:
n(1≤n≤9)
输出格式:
由1~n组成的所有不重复的数字序列,每行一个序列。每个数字保留5个常宽。
样例.in
3
样例.out
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

题目分析
经典的入门DFS,不多说,用一个数组来判重就可以了

代码

#include <bits/stdc++.h> 
using namespace std;

int vis[29],a[29],n;
string str;

void write()  //输出
{
    for (int i = 1; i <= n; i++)
        cout<<a[i]<<' ';
    cout<<endl;
}

void search(int k)
{
    if (k == n+1) write();  //完成搜索后输出
        else
            {
                for (int i = 1; i <= n; i++)
                    if (vis[i] == 0)   //没用过这个数
                        {
                            a[k]=i;  //记下来
                            vis[i]=1;   //设置占位符
                            search(k+1);   //向前一步搜索
                            vis[i]=0;    //回溯
                        }
            }
}

int main()
{
    cin>>n;

    search(1);

    return 0;   
}

除此,我们强大的C++还是有一个函数的,字符串都能排!
①字符串:

#include <bits/stdc++.h> 
using namespace std;

string str;

int main()
{

    getine(cin,str);

    while (next_permutation(str.begin(),str.end()))  //强大的stl函数
        cout<<str;

    return 0;
}

②数组:

#include <bits/stdc++.h> 
using namespace std;

int a[29],n;

int main()
{
    cin>>n;
    for (int i = 1; i <= n; i++)
        cin>>a[i];

    while (next_permutation(a+1,a+n+1))
        {
            for (int i = 1; i <= n; i++)
                cout<<a[i]<<' '; 
        }

    return 0;
}
                                                 **蒟蒻新星c_uizrp_dzjopkl原创**

猜你喜欢

转载自blog.csdn.net/c_uizrp_dzjopkl/article/details/81781889