字符串全排列Java实现
字符串全排列Java实现
陷阱:
注意考虑有重复的情况,比如 a,b,b
代码如下:
1 package com.secbro.test; 2 3 import java.util.ArrayList; 4 import java.util.HashSet; 5 import java.util.List; 6 import java.util.Set; 7 8 public class AllOrder { 9 10 private static Set<String> result = new HashSet<String>(); 11 12 public static void main(String[] args) { 13 char[] a = {'a','b','b'}; 14 15 permutation(a, 0, 2); 16 System.out.println(result); 17 } 18 19 20 private static void permutation(char[] a, int from, int to) { 21 if(a== null || from>to || from<0) { 22 return; 23 } 24 if(from == to) { 26 result.add(String.valueOf(a)); 27 } 28 for(int i = from; i <= to; i++) { 29 swap(a,i,from); 30 permutation(a, from +1,to); 31 swap(a,i,from); 32 } 33 } 34 35 36 private static void swap(char[]a, int left, int right) { 37 char temp = a[left]; 38 a[left] = a[right]; 39 a[right] = temp; 40 } 41 }
执行代码结果
[abb, bba, bab]