1. 程式人生 > >求不重複字元字串的全排列

求不重複字元字串的全排列

題目:輸入一個自付出,打印出該字串的所有排列。例如輸入字串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]