簡體   English   中英

如何找到具有所有不同字符的字符串的排列?

[英]How to find permutations of a string with all distinct characters?

我在一本書中找到了一段代碼,該代碼聲稱可以打印具有所有不同字符的字符串的所有排列:-

void permutation(String str) {
    permutation(str, "");
}
    
void permutation(String str, String prefix) {
    if (str.length() == 0) {
        System.out.println(prefix);
    } else {
        for (int i = 0; i < str.length(); i++) {
            String rem = str.substring(0, i) + str.substring(i + 1);
            permutation(rem, prefix + str.charAt(i));
        }
    }
}

rem變量在代碼中的作用是什么?

您可以可視化該過程。

static int indent = 0;
static String indent(int i) { return "  ".repeat(i); }

void permutation(String str) {
    System.out.println("permutation(\"" + str + "\")");
    ++indent;
    permutation(str, "");
}


void permutation(String str, String prefix) {
    System.out.println(indent(indent) + "permutation(\"" + str + "\", \"" + prefix + "\")");
    if (str.length() == 0) {
        System.out.println(indent(indent + 1) + "--> "+ prefix);
    } else {
        for (int i = 0; i < str.length(); i++) {
            String rem = str.substring(0, i) + str.substring(i + 1);
            ++indent;
            permutation(rem, prefix + str.charAt(i));
            --indent;
        }
    }
}

permutation("abc");

output

permutation("abc")
  permutation("abc", "")
    permutation("bc", "a")
      permutation("c", "ab")
        permutation("", "abc")
          --> abc
      permutation("b", "ac")
        permutation("", "acb")
          --> acb
    permutation("ac", "b")
      permutation("c", "ba")
        permutation("", "bac")
          --> bac
      permutation("a", "bc")
        permutation("", "bca")
          --> bca
    permutation("ab", "c")
      permutation("b", "ca")
        permutation("", "cab")
          --> cab
      permutation("a", "cb")
        permutation("", "cba")
          --> cba

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM