
If N = 3 and characters are = { a, b, c }
Then the four distinct sentences you can build:
a b c
a bc
ab c
abc
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a single integer ‘N’ denoting the number of characters.
The second line of each test case consists of a string ‘S’ denoting the characters.
For each test case, print all the sentences that can be built in separate lines.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 ≤ T ≤ 10
1 ≤ N ≤ 15
String ‘S’ consist of only lower case English alphabets
Time limit: 1 sec
If you have previously solved the problem of generating all subsets then you will probably find this problem very familiar.
You need to insert spaces between the characters to generate all possible sentences. Note that there are N-1 places and each place has two options, it will either have a space or not, this will finally lead to the generation of 2N-1 sentences. Also notice that even if you have duplicate characters still you won’t generate duplicate sentences, and the answer will still consist of 2N-1 sentences.
To generate all the sequences, you can easily backtrack to find all the sequences of size equal to N-1 and consisting of 0 and 1, where 1 denotes that the ith place has space between characters. You can store all the there strings in an array of array-of-strings and finally, sort it and return it.
The steps are as follows :
Sorted Doubly Linked List to Balanced BST
Longest Substring with K-Repeating Characters
Expression Add Operators
Gray Code Transformation
Count of Subsequences with Given Sum