劍指 Offer 38. 字串的排列
阿新 • • 發佈:2020-08-20
public String[] permutation(String s) { //顯然是遞迴加回溯 char[] c = s.toCharArray(); int n = c.length; //可能有重複元素,所以用set來儲存, Set<String> set = new HashSet<>(); char[] list = new char[n]; boolean[] visited = new boolean[n]; dfs(c,list,visited,0,set,n); String[] res = new String[set.size()]; int index = 0; Iterator<String> iterator = set.iterator(); while (iterator.hasNext()){ String st = iterator.next(); res[index++] = st; iterator.remove(); } return res; }private void dfs(char[] c, char[] list, boolean[] visited, int count, Set<String> set,int n) { if(count==n){ String s = new String(list); set.add(s); } for(int i = 0;i<n;i++){ if(!visited[i]){ list[count] = c[i]; visited[i]= true; dfs(c,list,visited,count+1,set,n); visited[i] = false; } } }