题目:输入一个自付出,打印出该字符串的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc,acb,bac,bca,cab,cba.
思路:将第一个字符与其后面字符分成两部分,将第一个字符与后面每个字符交换,不断递归。
代码如下:
import java.util.Arrays;
public class FullPermutation {
public static int k=0;
public void Permutation(char[] s)
{
if(s==null)
{
return;
}
Permutation( s, 0);
}
public void Permutation(char[] s,int position)
{
if(position==s.length-1)
{
System.out.println(++k+":"+Arrays.toString(s));
}
else
{
for(int i=position;i<s.length;i++)
{
char temp=s[i];
s[i]=s[position];
s[position]=temp;
Permutation(s, position+1);
temp=s[i];
s[i]=s[position];
s[position]=temp;
}
}
}
public static void main(String[] args) {
String s="abcd";
FullPermutation p=new FullPermutation();
p.Permutation(s.toCharArray());
}
}
输出结果:
1:[a, b, c, d]
2:[a, b, d, c]
3:[a, c, b, d]
4:[a, c, d, b]
5:[a, d, c, b]
6:[a, d, b, c]
7:[b, a, c, d]
8:[b, a, d, c]
9:[b, c, a, d]
10:[b, c, d, a]
11:[b, d, c, a]
12:[b, d, a, c]
13:[c, b, a, d]
14:[c, b, d, a]
15:[c, a, b, d]
16:[c, a, d, b]
17:[c, d, a, b]
18:[c, d, b, a]
19:[d, b, c, a]
20:[d, b, a, c]
21:[d, c, b, a]
22:[d, c, a, b]
23:[d, a, c, b]
24:[d, a, b, c]