回溯法(Java)
字符串的排列
http://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
思路:
回溯法 + set去重 + 集合排序
import java.util.*; public class Solution { public ArrayList<String> Permutation(String str) { Set<String> list = new HashSet<>(); backtrace(list,new StringBuilder(str),0); ArrayList result = new ArrayList<>(list); Collections.sort(result); return result; } public void backtrace(Set list,StringBuilder str,int index){ if(index + 1 == str.length()){ list.add(str.toString()); }else{ for(int i = index;i < str.length();i++){ char temp = str.charAt(index); str.setCharAt(index,str.charAt(i)); str.setCharAt(i,temp); backtrace(list,str,index + 1); temp = str.charAt(index); str.setCharAt(index,str.charAt(i)); str.setCharAt(i,temp); } } } }