DFS solution
Actually, my first dfs solution time limit was exceeded.
My thought is to do simple combinations dfs, just dfs on the search tree.
class Solution {
public:
int x = 0;
char arr[5] = {'a', 'e', 'i', 'o', 'u'};
void dfs(string s, int n, int index){
if(s.length() == n){
x += 1;
return;
}
for(int i = index; i < 5; i++){
dfs(s + arr[i], n, i);
}
}
int countVowelStrings(int n) {
dfs("", n, 0);
return x;
}
};
Later, I tried to use length to replace passing string and it worked.
class Solution {
public:
int x = 0;
char arr[5] = {'a', 'e', 'i', 'o', 'u'};
void dfs(int len, int n, int index){
if(len == n){
x += 1;
return;
}
for(int i = index; i < 5; i++){
dfs(len + 1, n, i);
}
}
int countVowelStrings(int n) {
dfs(0, n, 0);
return x;
}
};
DP solution
The dp solution is quite easy to think of, there are two methods to lead you there. The first one is to draw the different n and find the pattern. The second one is to analyze the different things between a e i o u.
We know a can match with 5 letters and e only match 4, and so on. by this pattern, you would know when n equals 3, a's pattern would include the pattern of e, i, o, u when n equals 2.
class Solution {
public:
int countVowelStrings(int n) {
//dp is simple, a matches 5 alp, b is 4, c is 3 ...
// {u, o, i, e, a}
//n = 1 -> {1, 1, 1, 1, 1} -> 5
//n = 2 -> {1, 2, 3, 4, 5} -> 15
//n = 3 -> {1, 3, 6, 10, 15} -> 35
int dp[5] = {1, 1, 1, 1, 1};
for(int i = 0; i < n; i++){
for(int j = 4; j >= 0; j--){
for(int k = 0; k < j; k++){
dp[j] += dp[k];
}
}
}
return dp[4];
}
};