直接套回溯模板,不容易出错,一遍过
用一个Set过滤下重复就可以了
import java.util.*; public class Solution { Set<String> res = new HashSet(); public ArrayList<String> Permutation(String str) { boolean[] flag = new boolean[str.length()]; back_track(str, "", flag); ArrayList<String> list = new ArrayList(); for(String s : res){ list.add(s); } return list; } public void back_track(String str, String now, boolean[] flag) { if(now.length() == str.length()){ res.add(now); return; } // for 选择 in xuan'ze'lie'b for(int i = 0;i<str.length();i++ ){ if( flag[i] ){ continue; }else{ // 做选择 now += str.charAt(i); flag[i] = true; // 回溯 back_track(str, now, flag) ; // 撤销选择 flag[i] = false; now = now.substring(0, now.length()-1); } } } }