To create an arrangement of a re-set (method)

Source: Internet
Author: User

Through the method of violence or Dfs can easily get n number of the full array, can generate a re-set, such as an array a[], require the output of the array of the entire arrangement, and the normal perfection arrangement, the array is likely to have duplicate number, so the method needs to be changed:

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)//here means that the number of repetitions can have up to two
{
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;
}

Violence:

#include "iostream"
#include "CString"
#include "Cstdio"
using namespace Std;
int n,book[21],a[21];
int ca=1;


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

for (int i=1;i<=n;i++)
{
int ok=1;
for (int j=2;j<step;j++)//Here j=2 means up to 2 duplicate numbers
if (a[j]==i) ok=0;
if (OK)
{
A[step]=i;
Print (step+1);
}
}
}

int main ()
{
int x=1;
while (scanf ("%d", &n)!=eof)
{
memset (A,0,sizeof (a));
if (x>1) cout<<endl;x++;
cout<< "Case" <<ca++<< ': ' <<endl;
Print (1);
}
return 0;
}

Finally, there is a STL function, more concise and useful

#include "iostream"
#include "algorithm"
using namespace Std;

int main ()
{
int n,p[10];
while (Cin>>n)
{
for (int i=0;i<n;i++) cin>>p[i];
Sort (p,p+n);
Do
{
for (int i=0;i<n;i++) cout<<p[i]<< ";
cout<<endl;
}while (Next_permutation (p,p+n));
}
return 0;
}

To create an arrangement of a re-set (method)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.