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

📅  最后修改于: 2021-06-25 11:32:35             🧑  作者: 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 permuations
    # 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!)