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 ;
}