首页 > 解决方案 > 从可以是 A、B 或 C 的 n 个字符中生成所有单词的函数

问题描述

我们需要创建一个函数,将ABC的所有组合组成,长度为n。我尝试制作一些东西,我只让它适用于 0、1 和 2,但我不知道如何使用递归或嵌套循环来制作它。

示例n=3

AAA,BAA,CAA,ABA,BBA,CBA,ACA,BCA,CCA,AAB,BAB,CAB,ABB,BBB,CBB,ACB,BCB,CCB,AAC,BAC,CAC,ABC,BBC,CBC,ACC,密件抄送、抄送


def generator (n):

    complete = [ ]

    words = ["A", "B", "C",]

    if (n==1):
        for word1 in words:
            complete.append(word1)
        return complete

    elif (n==0):
        return complete

    else:
        for word1 in words:
            for word2 in words:
                complete.append(word1+word2)

    return complete



n = int(input("Lenght n: "))

complete = (generator(n))

print(', '.join(complete))

标签: pythonrecursion

解决方案


使用递归解决java中的问题:

public static void main(String[] args) {
  String str = String.valueOf(words);
  printCombinations(str);
}

private static void printCombinations(String str) {
  printPermutation(str, "");
}

private static void printPermutation(String str, String str2) {
  if (str2.length() == str.length()) {
    //   printing the combination
    System.out.println(str2);
    return;
  }
  for (int i = 0; i < str.length(); i++) {
    printPermutation(str, str2 + str.charAt(i));
  }
}

推荐阅读