标签:move etc nta track char util for arraylist code
package myprac.LeetCode; import java.util.ArrayList; import java.util.List; public class StringPermutation { /* public static ArrayList<String> Permutation(String str) { ArrayList<String> list = new ArrayList<>(); if(str==null || str.length()==0){ return list; } char[] chars = str.toCharArray(); sort(list,0,chars); Collections.sort(list); return list; } private static void sort(ArrayList<String> list, int i, char[] chars) { if(i==chars.length-1){//i=2执行 list.add(new String(chars)); } for(int index = i;i<chars.length;i++){ if (index==i){ sort(list, index+1, chars); }else if(chars[i]!=chars[index]){ swap(chars,i,index); sort(list, index+1, chars); swap(chars,i,index); } } } private static void swap(char[] chars, int i, int index) { char c=chars[i]; chars[i]=chars[index]; chars[index] = c; } public static void main(String[] args) { String s = "aba"; System.out.println(Permutation(s)); }*/ public static List<List<Character>> permute(String str) { List<List<Character>> list = new ArrayList<>(); backtrack(list, new ArrayList<Character>(), str.toCharArray()); return list; } private static void backtrack(List<List<Character>> list, List<Character> tempList, char[] chars){ if(tempList.size() == chars.length){ list.add(new ArrayList<>(tempList)); } else{ for(int i = 0; i < chars.length; i++){ if(tempList.contains(chars[i])){ continue; } tempList.add(chars[i]); backtrack(list, tempList, chars); tempList.remove(tempList.size() - 1); } } } public static void main(String[] args){ String string = "abc"; System.out.println(permute(string)); } }
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
标签:move etc nta track char util for arraylist code
原文地址:https://www.cnblogs.com/q-1993/p/10864393.html