求不重复字符字符串的全排列

题目:输入一个自付出,打印出该字符串的所有排列。例如输入字符串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]




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值