递归解决全排列

Description

A permutation is a possible ordering of a set. For example, the permutations of a set {A,B,C} include ABC, ACB, BAC, BCA, CAB, CBA.
The number of permutations of a set of N elements is N!. The example set above has 3 elements and it has a number of 3!=6 permutations.
Given a line with N different characters, please print N! lines containing all different permutations of the N characters. These N! lines are printed in dictionary order.

Input

A line with N different characters。(1<=N<=8)

Output

N! lines containing all different permutations of the N characters. These N! lines are printed in dictionary order.

Sample Input
 Copy sample input to clipboard
ABCD
Sample Output
ABCD
ABDC
ACBD
ACDB
ADBC
ADCB
BACD
BADC
BCAD
BCDA
BDAC
BDCA
CABD
CADB
CBAD
CBDA
CDAB
CDBA
DABC
DACB
DBAC
DBCA
DCAB
DCBA


这道题要求输出字母的全排列,可以运用递归解决。

下面是代码:

#include
#include
using namespace std;
void premutation(string pre,string s)
{
if(s=="") cout<for(int i=0;i{
  string str=s;
premutation(pre+s[i],str.erase(i,1));
}

}
int main()
{
string s,pre="";
cin>>s;
premutation(pre,s);
return 0;
}


这道题用到了erase函数,我们可以看一下它的用法:

string s;

1. s.erase(2.3) 删除第二个字符后(不包括)的三个字符,即删除s[2],s[3],s[3]。eg. 12345 ,删除3.4.5,剩下1.2.

2. s.erase(s.begin()+2,s.end()-1) 删除之间的字符,是不是可以这样理解,s.begin()==s[0],s.begin()+2==s[2].同理,在下例中,s.end()-1==s[3]。eg.12345,删除34,输出125.

3. s.erase(posion) .......(这个以后来补充。。。。。)

你可能感兴趣的:(c&&c++)