Count Vowels Permutation LeetCode solution in Java

1
class Solution {
2
private long[][] dp;
3
private int mod = (int) 1e9 + 7;
4

5
public int countVowelPermutation(int n) {
6
dp = new long[6][n + 1];
7
if (n == 1) return 5;
8

9
for (int i = 0; i < 5; i++) dp[i][0] = 1;
10

11
helper(n, 'z');
12
return (int) dp[5][n];
13
}
14

15
private long helper(int n, char vowel) {
16
long ans = 0;
17
if (n == 0) return 1;
18

19
if (vowel == 'z') // we are using z for our convenience just to add Permutations of all Vowels
20
{
21
ans =
22
(ans
23
+ helper(n - 1, 'a')
24
+ helper(n - 1, 'e')
25
+ helper(n - 1, 'i')
26
+ helper(n - 1, 'o')
27
+ helper(n - 1, 'u'))
28
% mod;
29
dp[5][n] = ans;
30
}
31
// from here as per our assumptions of Vowels we will make calls & store results
32
else if (vowel == 'a') // for Nth number we would store Result for "a" in dp[0][n]
33
{
34
if (dp[0][n] != 0) return dp[0][n];
35
ans = (ans + helper(n - 1, 'e')) % mod;
36
dp[0][n] = ans;
37
} else if (vowel == 'e') // for Nth number we would store Result for "e" in dp[1][n]
38
{
39
if (dp[1][n] != 0) return dp[1][n];
40
ans = (ans + helper(n - 1, 'a') + helper(n - 1, 'i')) % mod;
41
dp[1][n] = ans;
42
} else if (vowel == 'i') // for Nth number we would store Result for "i" in dp[2][n]
43
{
44
if (dp[2][n] != 0) return dp[2][n];
45
ans =
46
(ans + helper(n - 1, 'a') + helper(n - 1, 'e') + helper(n - 1, 'o') + helper(n - 1, 'u'))
47
% mod;
48
dp[2][n] = ans;
49
} else if (vowel == 'o') // for Nth number we would store Result for "o" in dp[3][n]
50
{
51
if (dp[3][n] != 0) return dp[3][n];
52
ans = (ans + helper(n - 1, 'i') + helper(n - 1, 'u')) % mod;
53
dp[3][n] = ans;
54
} else // for Nth number we would store Result for "u" in dp[4][n]
55
{
56
if (dp[4][n] != 0) return dp[4][n];
57
ans = (ans + helper(n - 1, 'a')) % mod;
58
dp[4][n] = ans;
59
}
60

61
return ans;
62
}
63
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0