【CC150】字符串(含重复值)的全排列组合
题目说明:编写一个方法,确认某字符串的所有排列组合。
输入1:ab
输出1:
2
ab ba
输入2:aab(含重复值)
输出2:
3
aba baa aab
思路:
1.因为要去重,首先想到了set。
如果使用arrayList就要考虑如何去重的问题,
2.全排列的问题怎么搞?示例:abc
第一位有三种情况:a,b,c
当第一位确定了a ,第二位有两种情况:b,c
当第二位确定了b,第三位有一种情况:c
所以全排列组合有3×2×1=6种
那该怎么编程代码呢?
可以理解为插空。
第一个当确定是a,可以在a的前面插空,后面插空;(一个元素的排列组合有1种)->可以理解为初始化集合的第一个元素
当第二个确定是b,现在的组合就是ab 和ba;(两个元素的排列组合有2种)->可以理解为在前一 个集合中插空
当第三个c插空进来,在ab的前面,后面,中间插空,现在的组合就是cab,abc,a cb ,cba,bac,bca(三个元素的排列组合有6种)
当第一位确定是…,这一个步可以理解为从原字符串中取出元素
代码如下:
1 public class case8_permutation2去重 { 2 3 public static void main(String[] args) { 4 case8_permutation2去重 obj= new case8_permutation2去重(); 5 Set<String> res=new HashSet<String>() ; 6 //ArrayList<String> res=new CopyOfcase8_permutation().permutations("aaab"); 7 res=obj.permutations("aab"); 8 // res=obj.permutations("lanqiao"); 9 System.out.println(res.size()); 10 System.out.println(res); 11 } 12 13 private static Set<String> permutations(String s) { 14 int n=s.length(); 15 Set<String> res=new HashSet<String>() ; 16 res.add(s.charAt(0)+"");//初始化 17 for (int i = 1; i <n; i++) {//遍历给定字符串; 18 char c=s.charAt(i); 19 Set<String> res_new=new HashSet<String>() ; 20 for (String str : res) {//遍历上一次获得的排列; 21 //在已有的排列前面加入c; 22 String newStr=c+str; 23 res_new.add(newStr); 24 //在已有的排列后面加入c; 25 newStr=str+c; 26 res_new.add(newStr); 27 //在已有的排列中间加入c; 28 for (int j = 1; j < str.length(); j++) { 29 newStr=str.substring(0, j)+c+str.substring(j); 30 res_new.add(newStr); 31 } 32 33 } 34 res=res_new; 35 } 36 return res; 37 38 } 39 40 }
以上代码输出:
3
[aba, baa, aab]
下一篇给出使用回溯法解决该问题。
浙公网安备 33010602011771号