通过暴力或者dfs的方法可以很容易地得到n个数的全排列,可生成可重集的呢,例如给出一个数组a[],要求输出这个数组的全排列,与普通的求全排列不同,数组中很可能存在重复的数,所以方法都需要改一改:

 

DFS

#include"iostream"
#include"cstring"
#include"cstdio"
using namespace std;
int n,book[21],a[21];
int ca=1;

void dfs(int step)
{
    if ((step == n))
    {
        for(int i=1; i<n; i++) cout<<a[i]<<' ';
        cout<<a[n]<<endl;
        return;
    }
    for(int i=1; i<=n; i++)
        if(book[i]<=2)          //这里表示重复的数最多可以有两个
        {
            a[step+1]=i;
            book[i]++;
            dfs(step+1);
            book[i]--;
        }
}
int main()
{
    int x=1;
    while(scanf("%d",&n)!=EOF)
    {
//a[1]=1;
        if(x>1) cout<<endl;
        x++;
        cout<<"Case "<<ca++<<':'<<endl;
        dfs(0);
    }
    return 0;
}
View Code

相关文章:

  • 2022-12-23
  • 2021-09-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-30
  • 2021-04-19
猜你喜欢
  • 2021-06-02
  • 2021-10-31
  • 2021-10-17
  • 2022-12-23
  • 2021-06-20
  • 2021-10-08
  • 2022-12-23
相关资源
相似解决方案