首页 > 其他 > 详细

[Algo] 643. All Permutations of Subsets

时间:2020-04-01 10:28:24      阅读:68      评论:0      收藏:0      [点我收藏+]

Given a string with no duplicate characters, return a list with all permutations of the string and all its subsets.

 

Examples

Set = “abc”, all permutations are [“”, “a”, “ab”, “abc”, “ac”, “acb”, “b”, “ba”, “bac”, “bc”, “bca”, “c”, “cb”, “cba”, “ca”, “cab”].

Set = “”, all permutations are [“”].

Set = null, all permutations are [].

 

public class Solution {
  public List<String> allPermutationsOfSubsets(String set) {
    // Write your solution here
    List<String> list = new ArrayList<>();
    Set<Character> charSet = new HashSet<>();
    helper(set, charSet, 0, list, new StringBuilder());
    return list;
  }

  private void helper(String str, Set<Character> charSet, int num, List<String> result, StringBuilder sb) {
    result.add(sb.toString());
    for (int i = 0; i < str.length(); i++) {
      if (charSet.contains(str.charAt(i))) {
        continue;
      }
      sb.append(str.charAt(i));
      charSet.add(str.charAt(i));
      helper(str, charSet, num + 1, result, sb);
      sb.deleteCharAt(sb.length() - 1);
      charSet.remove(str.charAt(i));
    }
  }
}

 

[Algo] 643. All Permutations of Subsets

原文:https://www.cnblogs.com/xuanlu/p/12610087.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!