Generating all permutations of a given string

前端 未结 30 1664
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  太阳男子
    2020-11-21 06:40

    Another simple way is to loop through the string, pick the character that is not used yet and put it to a buffer, continue the loop till the buffer size equals to the string length. I like this back tracking solution better because:

    1. Easy to understand
    2. Easy to avoid duplication
    3. The output is sorted

    Here is the java code:

    List permute(String str) {
      if (str == null) {
        return null;
      }
    
      char[] chars = str.toCharArray();
      boolean[] used = new boolean[chars.length];
    
      List res = new ArrayList();
      StringBuilder sb = new StringBuilder();
    
      Arrays.sort(chars);
    
      helper(chars, used, sb, res);
    
      return res;
    }
    
    void helper(char[] chars, boolean[] used, StringBuilder sb, List res) {
      if (sb.length() == chars.length) {
        res.add(sb.toString());
        return;
      }
    
      for (int i = 0; i < chars.length; i++) {
        // avoid duplicates
        if (i > 0 && chars[i] == chars[i - 1] && !used[i - 1]) {
          continue;
        }
    
        // pick the character that has not used yet
        if (!used[i]) {
          used[i] = true;
          sb.append(chars[i]);
    
          helper(chars, used, sb, res);
    
          // back tracking
          sb.deleteCharAt(sb.length() - 1);
          used[i] = false;
        }
      }
    }
    

    Input str: 1231

    Output list: {1123, 1132, 1213, 1231, 1312, 1321, 2113, 2131, 2311, 3112, 3121, 3211}

    Noticed that the output is sorted, and there is no duplicate result.

提交回复
热议问题