【问题标题】:How to go about making this type of combination?如何进行这种组合?
【发布时间】:2013-12-23 05:48:20
【问题描述】:

我有一个由四个字母组成的字母串,例如 ASDF,我想使用这些字母找到所有 3(三)个字母组合,并且三个字母组合不需要形成一个真实的单词。例如。

AAA AAS AAD AAF ADA ADS 添加 ADF ………………………………………………………………………… SSA SSD SSF SSS

我对 Java 比较陌生,刚刚学会了如何使用 String 类以及使用循环和条件语句。我知道如何做到这一点的唯一方法是通过大量且非常乏味的 for 循环和 if 语句来解释可能出现的每一种可能性。这看起来像:

    public static void main(String[] args)
    {
      String combo = "";
      for(int counter = 1; counter <= 16; counter++){
           combo = "A";
           if(counter == 1){
              combo = combo + "AA";
           }
         // This would continue on for all the possibilities starting with "A" and
         // then move on to "S" as the lead character
       }
    }

我知道这是解决这个问题的最糟糕的方法之一,但我真的不知道如何用另一种方法来解决这个问题。如果我有 3 个字母并进行 3 个字母组合会更容易,因为这样我就可以从数组中获取每个字母并重新排列它们,但是由于我只使用 4 个字母中的 3 个,所以更加困难。 关于如何以更有效的方式完成此任务的任何建议?

【问题讨论】:

  • 欢迎来到 Stack Overflow!第一个问题好。 +1

标签: java string combinations nested-loops conditional-statements


【解决方案1】:

使用recursive function

像这样(未经测试,我的笔记本电脑上没有 Java 编译器)。 使用 StringBuilder 可能会提高性能。

static void printAllPossibilities(String charSet, int length) {
  printAllPossibilities_(charSet, length, "");
}

static void printAllPossibilities_(String charSet, int length, String temp) {
  if (length == 0) {
    System.out.println(temp);
    return;
  }
  for (int i = 0; i < charSet.length(); i++)
    printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
}

用法:

printAllPossibilities("ASDF", 4); // Print all 4-letter combinations out of "ASDF"
printAllPossibilities("bar", 2); // Print all 2-letter combinations out of "bar"

【讨论】:

  • 哦,那不是我,我还在努力了解如何使用递归函数。
  • 我并没有责怪你投反对票;)我添加了一个如何使用它的示例。
  • 当我否决它时,它是一个 公然 占位符答案,没有任何细节或用处。
  • 它从来都不是占位符。有人向它征求意见,我给了一些建议。仅仅因为一开始没有代码并不意味着它不能回答问题。
  • 非常感谢,我能够得到答案,我真的很惊讶递归函数的强大!如果我有足够的代表,我会投票给你。
【解决方案2】:

对于一般情况(M 中 N 个字符的所有组合),@Qntm 的解决方案正是您所需要的......但是,如他所说,使用 StringBuilder,只需更改最后一个字符而不是构造字符串比如'temp + charSet.charAt(i)'。

如果您需要 N 中的 3 个字符,则只需执行 3 个嵌套循环会更容易:

for (int char1 = 0; char1 < charSet.length(); char1++) {
    for (int char2 = 0; char2 < charSet.length(); char2++) {
        for (int char3 = 0; char3 < charSet.length(); char3++) {
            System.out.println(""+charSet.charAt(char1)+charSet.charAt(char2)+charSet.charAt(char3));
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多