【问题标题】:How to find permutations of a string with all distinct characters?如何找到具有所有不同字符的字符串的排列?
【发布时间】:2020-08-11 12:58:07
【问题描述】:

我在一本书中发现了一段代码,它声称可以打印具有所有不同字符的字符串的所有排列:-

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变量在代码中的作用是什么?

【问题讨论】:

  • 取一个像"abc" 这样的字符串并通过函数来​​处理它。尝试理解代码中的每一步。拿一张纸写下部分结果。
  • 您知道 permutation(String, String) 在某些条件下使用调整参数调用自身的方法,不是吗?
  • 我不明白字符串 rem = something。为什么这个 rem 是必需的?
  • @Jeet 这不是“必需的”,但这个临时变量使代码更具可读性。你可以在permutation-call 中写下所有内容,但这会是一个很长的声明。
  • 检查javadoc for substringstr.substring(0,i) + str.substring(i +1)实际上给出了str,去掉了i'th字符。

标签: java string recursion


【解决方案1】:

您可以将过程可视化。

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");

输出

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2012-10-24
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    相关资源
    最近更新 更多