📜  生成句子中单词的所有可能排列

📅  最后修改于: 2021-09-08 11:34:19             🧑  作者: Mango

给定一个字符串S ,任务是打印句子中所有单词的排列。

例子:

方法:可以使用递归解决给定的问题。请按照以下步骤解决问题:

  1. 遍历句子并使用split()将句子中出现的单词按空格拆分,并将它们存储在列表中。
  2. 使用内置的Python函数itertools.permutations()排列列表。
  3. 遍历排列并将每个排列转换为列表。
  4. 打印这些列表。

下面是上述方法的实现:

Python3
# Python implementation of
# the above approach
 
from itertools import permutations
 
 
# Function to generate permutations
# of all words in a sentence
def calculatePermutations(sentence):
 
    # Stores all words in the sentence
    lis = list(sentence.split())
 
    # Stores all possible permutations
    # of words in this list
    permute = permutations(lis)
 
    # Iterate over all permutations
    for i in permute:
       
        # Convert the current
        # permutation into a list
        permutelist = list(i)
         
        # Print the words in the
        # list separated by spaces
        for j in permutelist:
            print(j, end = " ")
             
        # Print a new line
        print()
 
 
# Driver Code
if __name__ == '__main__':
 
    sentence = "sky is blue"
    calculatePermutations(sentence)


输出:
sky is blue 
sky blue is 
is sky blue 
is blue sky 
blue sky is 
blue is sky

时间复杂度: O(N!),其中 N 表示句子中的单词数。
辅助空间: O(N!)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live