判断要交换的位置之前是否有和要交换的相同,存在相同的就不对本次子序列排列了
public void permute(char[] arr, int index) { if(index == arr.length-1) { System.out.println(new String(arr)); return ; } for(int i=index;i<arr.length;i++) { if(!isNeedSwap(arr, index ,i)) continue; swap(arr, i, index); permute(arr,index+1); swap(arr, i, index); } } private void swap(char[] arr, int a, int b) { if(arr[a] != arr[b]) { arr[a] = (char) (arr[a] ^ arr[b]); arr[b] = (char) (arr[a] ^ arr[b]); arr[a] = (char) (arr[a] ^ arr[b]); } } private boolean isNeedSwap(char[] arr, int from, int to) { boolean flag = true; for (int i = from; i < to; i++) { if (arr[to] == arr[i]) { flag = false; break; } } return flag; } public static void permuteTest() { char[] cArr= new char[] {'a', 'b', 'b', 'b'}; self.permute(cArr, 0); } public static void main(String[] args) { permuteTest(); }