题解 | #字符串的排列#
字符串的排列
http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
使用Set去重
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class Solution {
public ArrayList<String> Permutation(String str) {
boolean[] visited=new boolean[str.length()];
ArrayList<String> res=new ArrayList<>();
StringBuffer path=new StringBuffer();
Set<String> set=new HashSet<>();
backtracking(str, visited, set, res, path);
return res;
}
public void backtracking(String str, boolean[] visited, Set<String> set, ArrayList<String> res, StringBuffer path){
if(path.length()==str.length()&&!set.contains(path.toString())){
set.add(path.toString());
res.add(path.toString());
return;
}
for(int i=0; i<str.length();i++){
if(visited[i]){
continue;
}
visited[i]=true;
path.append(str.charAt(i));
backtracking(str, visited, set, res, path);
path.deleteCharAt(path.length()-1);
visited[i]=false;
}
}
}