排列算法
package org.example.permandcombine; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author xianzhe.ma * @date 2021/11/3 */ public class Permutation { public static ArrayList<String> Permutation(String str) { int length = str.length(); List<String> inputList = new ArrayList<>(); for (int i = 0;i<length;i++) { char c = str.charAt(i); String temp = String.valueOf(c); inputList.add(temp); } String[] array = new String[length]; inputList.toArray(array); ArrayList<String> result = new ArrayList<>(); doPerm(array, 0, length, result); Set<String> set = new HashSet<>(); set.addAll(result); ArrayList<String> result2 = new ArrayList<>(); result2.addAll(set); return result2; } public static void main (String[] args) { String str = "ABC"; ArrayList<String> list = Permutation(str); for (String str1 : list) { System.out.println(str1); } } public static void doPerm(String[] array, int start, int end, ArrayList<String> result) { if (start == end) { int size = array.length; StringBuilder stringBuilder = new StringBuilder(); for (int i=0;i<size;i++) { stringBuilder.append(array[i]); } result.add(stringBuilder.toString()); return; } for (int i= start;i<end;i++) { swap(array, start, i); doPerm(array,start+1,end, result); swap(array, start, i); } } public static void swap(String[] array, int i, int j) { String temp = array[i]; array[i] = array[j]; array[j] = temp; } }