【LeetCode】1641. Count Sorted Vowel Strings(动态规划)
Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.
A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.
思路
每组n中五个字符以每个字符为开头的个数相加;
如:
当首位为a,如果此时有n位,则剩下的n-1位可以是n-1位中所有结果;
当首位为e,如果此时有n位,则剩下的n-1位可以是n-1位中除去a开头的所有结果。
实现
public int countVowelStrings(int n) {
int temp = 0;
// 初始化n为1
int dp[] = new int[]{1,1,1,1,1};
for(int i = 2;i <= n;i++){
//n-1的和
int sum = 0;
for(int j = 4;j >= 0;j--){
sum += dp[j];
//sum为n-1位满足结果的个数
dp[j] = sum;
}
}
// 最后遍历数组累加
for(int i : dp){
temp += i;
}
return temp;
}