zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    luogu 3388 【模板】割点(割顶)
    bzoj 3624 免费道路
    bzoj 1179 Atm
    bzoj 2428 均分数据
    luogu 4429 染色
    luogu 4427 求和
    luogu 1121 环状最大两段子段和
    hdu 4777 Queue
    hdu 5492 Find a path
    hdu 5441 Travel
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8690075.html
Copyright © 2011-2022 走看看