Python 字符串组合算法:高效获取所有排列组合
可以使用递归的方式来计算字符串的所有组合方式。
以下是一个示例代码:
def get_combinations(string):
combinations = []
if len(string) == 1:
return [string]
else:
for i in range(len(string)):
first = string[i]
rest = string[:i] + string[i+1:]
for combination in get_combinations(rest):
combinations.append(first + combination)
return combinations
string = 'abc'
combinations = get_combinations(string)
print(combinations)
输出结果为:['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
上述代码中,get_combinations函数接收一个字符串作为输入,并返回一个包含所有组合的列表。如果字符串长度为1,则直接返回该字符串。否则,遍历字符串中的每个字符,并将其与剩余字符的组合递归地添加到结果列表中。最后返回结果列表。
在示例中,输入字符串为'abc',输出结果为['abc', 'acb', 'bac', 'bca', 'cab', 'cba'],即所有可能的组合方式。
原文地址: https://www.cveoy.top/t/topic/pZ82 著作权归作者所有。请勿转载和采集!