列出给定长度的所有可能值算法

List all possible value algorithm with given length

我知道 python 中的库可以更轻松地产生所有可能的价值。但是我想知道里面的算法。

我期待一个像这样工作的函数

def listPossiblePair(length:int,possibleValue:set) -> list:

考虑在我的例子中可能显示的值只有 0 和 1。

如果长度为 3,则函数将 return 该可能值的所有可能对

listPossiblePair(3,{0,1})

会return

[[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]

这是另一个例子

另一个例子:

listPossiblePair(2,{0,1,2})

会return

[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
# Python 3 program to print all
# possible strings of length k
     
# The method that prints all
# possible strings of length k.
# It is mainly a wrapper over
# recursive function printAllKLengthRec()
def printAllKLength(set, k):
 
    n = len(set)
    printAllKLengthRec(set, "", n, k)
 
# The main recursive method
# to print all possible
# strings of length k
def printAllKLengthRec(set, prefix, n, k):
     
    # Base case: k is 0,
    # print prefix
    if (k == 0) :
        print(prefix)
        return
 
    # One by one add all characters
    # from set and recursively
    # call for k equals to k-1
    for i in range(n):
 
        # Next character of input added
        newPrefix = prefix + set[i]
         
        # k is decreased, because
        # we have added a new character
        printAllKLengthRec(set, newPrefix, n, k - 1)
 
# Driver Code
if __name__ == "__main__":
     
    print("First Test")
    set1 = ['a', 'b']
    k = 3
    printAllKLength(set1, k)
     
    print("\nSecond Test")
    set2 = ['a', 'b', 'c', 'd']
    k = 1
    printAllKLength(set2, k)
 
# This code is contributed
# by ChitraNayal

参考:https://www.geeksforgeeks.org/print-all-combinations-of-given-length/