LF.63.All SubsetsII
Given a set of characters represented by a String, return a list containing all subsets of the characters.
Assumptions
There could be duplicate characters in the original set.
Examples
Set = "abc", all the subsets are ["", "a", "ab", "abc", "ac", "b", "bc", "c"]
Set = "abb", all the subsets are ["", "a", "ab", "abb", "b", "bb"]
Set = "", all the subsets are [""]
Set = null, all the subsets are []
1 public List<String> subSets(String set) { 2 // Write your solution here. 3 List<String> res = new ArrayList<>(); 4 if (set == null) { 5 return res; 6 } 7 char[] chars = set.toCharArray(); 8 //排列一下,为了去重复 9 Arrays.sort(chars); 10 /* 11 * 使用字典是错误的,因为 AAB 和 ABA 都算是一样的,并没有办法用字典来规范 12 * */ 13 StringBuilder sb = new StringBuilder(); 14 dfs(chars, res, 0, sb); 15 return res; 16 } 17 18 private void dfs(char[] chars, List<String> res, int index, StringBuilder sb) { 19 //base case: reaches the bottom 20 if (index == chars.length) { 21 res.add(sb.toString()); 22 return; 23 } 24 //case 1 : +chars[index] 25 sb.append(chars[index]); 26 dfs(chars, res, index + 1, sb); 27 sb.deleteCharAt(sb.length() - 1); 28 while (index< chars.length -1 && chars[index] == chars[index+1]){ 29 index++ ; 30 } 31 //case 2 : + "" 32 sb.append(""); 33 dfs(chars, res, index + 1, sb); 34 //since added "", no need to remove 35 36 }