Generate all possible permutations of words in a Sentence
Given a string S, the task is to print permutations of all words in a sentence.
Examples:
Input: S = “sky is blue”
Output:
sky is blue
sky blue is
is sky blue
is blue sky
blue sky is
blue is skyInput: 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
Approach: The given problem can be solved using recursion. Follow the steps below to solve the problem:
- Traverse the sentence and split the words present in the sentence by spaces using split() and store them in a list.
- Permute the list using built-in python functions itertools.permutations().
- Traverse the permutations and convert each permutation to a list.
- Print these lists.
Below is the implementation of the above approach:
Python3
|
sky is blue sky blue is is sky blue is blue sky blue sky is blue is sky
Time Complexity: O(N!), where N denotes the number of words in a sentence.
Auxiliary Space: O(N!)
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment