[Leetcode学习-c++&java]Count Sorted Vowel Strings

问题:

难度:medium

说明:

给出一个数字 N,然后根据 a e i o u 五个元音字母进行组合,组合一个 N 长度的字符串。然后每个原音后面只能够组合 按 aeiou 排序的 自己位置或后面位置的字母,如 a 拼接 aa ae ai ao au,而 e 拼接 ee ei eo eu,按照 aeiou 顺序,每个字母后面只能跟一个和他一样的或者位置比他后的元音字母。

题目连接:https://leetcode.com/problems/count-sorted-vowel-strings/

输入范围:

  • 1 <= n <= 50 

输入案例:

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

我的代码:

具体可以看到,结尾的字母是决定数量的关键,那么

当 n = 1  a e i o u 结尾的数量:1 1 1 1 1,而排列总和是 1 + 1 + 1 + 1 + 1 = 5

当 n = 2  a e i o u 结尾的数量:1 2 3 4 5,而排列总和是 1 + 2 + 3 + 4 + 5 = 15

当 n = 3  a e i o u 结尾的数量:1 3 6 10 15,而排列总和是 35(自行画图分析,可以查看到, a 结尾一定是 5 个排列, e 为 4个,如此类推,统计一下结尾字母就行)

所以打表就行,反正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++:

因为数量少,这次跑的飞起

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];
		}
	}
};

 

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页