Approach: The idea to solve this problem is to visualize this as a Graph Problem. From the given rules a directed graph can be constructed, where an edge from u to v means that v can be immediately written after u in the resultant strings. The problem reduces to finding the number of N-length paths in the constructed directed graph. Follow the steps below to solve the problem:
Let the vowels a, e, i, o, u be numbered as 0, 1, 2, 3, 4 respectively, and using the dependencies shown in the given graph, convert the graph into an adjacency list relation where the index signifies the vowel and the list at that index signifies an edge from that index to the characters given in the list.
Initialize a 2D array dp[N + 1] where dp[N][char] denotes the number of directed paths of length N which end at a particular vertex char.
Initialize dp[i][char] for all the characters as 1, since a string of length 1 will only consist of one vowel in the string.
For all possible lengths, say i, traverse over the directed edges using variable u and perform the following steps:
Update the value of dp[i + 1][u] as 0.
Traverse the adjacency list of the node u and increment the value of dp[i][u] by dp[i][v], that stores the sum of all the values such that there is a directed edge from node u to node v.
After completing the above steps, the sum of all the values dp[N][i], where i belongs to the range [0, 5), will give the total number of vowel permutations.
Below is the implementation of the above approach:
Please Login to comment...