Recursively output the full arrangement of n different elements

Source: Internet
Author: User

How to output the full arrangement of n elements, such as ABC, a total of ABC, ACB, Bac, BCA, cab, and CBA. Generally, A string with n elements has n! .

We can generate the arrangement of n elements as a trade-off problem, such as the element string ABC. For the arrangement method starting with a, we can use the following method for selection. (1) select B to form AB,

Continue to select C to create ABC. The new string is generated and ends. But in the first step, you can choose not B, and then continue to search. Then, only C and C are selected to form the AC, and B is selected as the last element.

Generates a new string named ACB. In this way, we need to use a flag array to mark which elements have been used and which elements have not been used. ReferencesProgramAs follows:

 

 

Code
// Ex01b. cpp: defines the entry point of the console application.
//

# Include " Stdafx. h "

# Include<String>
# Include<Iostream>
Using NamespaceSTD;

IntUsed [100]={0};
IntTotal= 0;

Void Perm ( Int N, Int Count, String & Temp, String SRC)
{
If (Count = N)
{
// Locate a column and Output
Cout < Temp < Endl;
Total ++ ;
Return ;
}
Else
{
For ( Int J =   0 ; J < N; j ++ )
{
If (Used [J] =   0 )
{
Used [J] =   1 ; // Select SRC [I] and set the flag.
Temp + = SRC [J];
Perm (n, count + 1 , Temp, Src );
Temp. Erase (temp. Length () - 1 ); // If SRC [I] is not selected, the flag is reset.
Used [J] =   0 ;
}
}

}
}

Int _ Tmain ( Int Argc, _ tchar * Argv [])
{
String SRC, temp;
CIN > SRC;
For ( Int I =   0 ; I < ( Int ) SRC. Length (); I ++ )
{
Used [I] =   1 ;
Temp = SRC [I];
Perm (( Int ) SRC. Length (), 1 , Temp, Src );
Used [I] =   0 ;
}
Cout < Total < " Situation " < Endl;
Return   0 ;
}

 

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.