给定字符串S ,任务是打印句子中所有单词的排列。
例子:
Input: S = “sky is blue”
Output:
sky is blue
sky blue is
is sky blue
is blue sky
blue sky is
blue is sky
Input: S =” Do what you love”
Output:
Do what you love
Do what love you
Do you what love
Do you love what
Do love what you
Do love you what
what Do you love
what Do love you
what you Do love
what you love Do
what love Do you
what love you Do
you Do what love
you Do love what
you what Do love
you what love Do
you love Do what
you love what Do
love Do what you
love Do you what
love what Do you
love what you Do
love you Do what
love you what Do
方法:可以使用递归来解决给定的问题。请按照以下步骤解决问题:
- 遍历句子,并使用split()用空格将句子中存在的单词分开,并将它们存储在列表中。
- 使用内置的Python函数itertools.permutations()置换列表。
- 遍历排列并将每个排列转换为列表。
- 打印这些列表。
下面是上述方法的实现:
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!)