problem:
Difficulty: medium
Description:
Give a number N, and then combine the five vowels of aeiou to form a string of length N. Then each original sound can only be combined with letters in its own or subsequent positions sorted by aeiou, such as a splicing aa ae ai ao au, and e splicing ee ei eo eu. According to the aeiou order, each letter can only be followed by a and He is the same or the position of the vowel after him.
Subject link: https://leetcode.com/problems/count-sorted-vowel-strings/
Input range:
1 <= n <= 50
Enter the case:
Example 1:
Input: n = 1
Output: 5
Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].
Example 2:
Input: n = 2
Output: 15
Explanation: The 15 sorted strings that consist of vowels only are
["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].
Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
Example 3:
Input: n = 33
Output: 66045
My code:
Specifically, you can see that the letter at the end is the key to determining the number, then
When n = 1 the number at the end of aeiou: 1 1 1 1 1, and the sum of the permutations is 1 + 1 + 1 + 1 + 1 = 5
When n = 2 the number at the end of aeiou: 1 2 3 4 5, and the sum of the permutations is 1 + 2 + 3 + 4 + 5 = 15
When n = 3, the number of aeiou endings: 1 3 6 10 15, and the total number of permutations is 35 (you can draw and analyze by yourself, you can see that the end of a must be 5 permutations, and e is 4, and so on. Just count the ending letters. )
So just hit the table, anyway, within 50.
Java:
class Solution {
private static int[] arr = new int[5], map = new int[50];
static { // 静态代码块打表
Arrays.fill(arr, 1);
for(int i = 1;i < 51;i ++) {
int temp = i - 1, n = i;
for(int j : arr) map[temp] += j;
for(int j = 1;j < 5;j ++) arr[j] += arr[j - 1];
}
}
public int countVowelStrings(int n) {
return map[n - 1];
}
}
C++:
Because of the small number, this time I ran up
static int arr[5] = {1,1,1,1,1}, cache[50], temp;
static bool flag = true;
class Solution {
public:
int countVowelStrings(int n) {
if (flag) {
build(); flag = false;
}
return cache[n - 1];
}
void build() {
memset(cache, 0, 50);
for (int i = 1; i < 51; i++) {
temp = i - 1;
for (int j = 0; j < 5; j ++) cache[temp] += arr[j];
for (int j = 1; j < 5; j++) arr[j] += arr[j - 1];
}
}
};