输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = “abc” 输出:[“abc”,“acb”,“bac”,“bca”,“cab”,“cba”]
怎么把List<String> 转成String[]; res.toArray(new String[res.size()]);
class Solution { public String[] permutation(String s) { List<String> res = new ArrayList<>(); StringBuffer temp = new StringBuffer(); boolean[] visited = new boolean[s.length()]; char[] chars = s.toCharArray(); Arrays.sort(chars); backtrack(res,temp, visited, chars); return res.toArray(new String[res.size()]); } public void backtrack(List<String> res, StringBuffer temp, boolean[] visited , char[] chars) { if(temp.length()==chars.length){ res.add(temp.toString()); return; } for(int i =0;i<chars.length;i++){ if(!visited[i] &&( i==0 || chars[i] !=chars[i-1] || visited[i-1])) { temp.append(chars[i]); visited[i] = true; backtrack(res,temp, visited, chars); visited[i] = false; temp.deleteCharAt(temp.length()-1); } } } }