1641. Count Sorted Vowel Strings

问题:

用a,e,i,o,u构成字符串,前面的字符一定是后面字符的字母序之前。

构成长度为n的字符串,有多少种方法。

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
 
Constraints:
1 <= n <= 50 

  

解法:Backtracking(回溯算法)

状态:第pos位上可选择的字符。到目前为止选择的结果为path。

选择:path最后一位之后的字符。

递归退出条件:pos==n

代码参考:

 1 class Solution {
 2 public:
 3     void backtrack(int& res, int n, vector<int>& path) {
 4         if(path.size()==n) {
 5             res++;
 6             return;
 7         }
 8         for(int i=(path.size()!=0?path.back():0); i<5; i++) {
 9             path.push_back(i);
10             backtrack(res, n, path);
11             path.pop_back();
12         }
13         return;
14     }
15     int countVowelStrings(int n) {
16         int res=0;
17         vector<int> path;
18         backtrack(res, n, path);
19         return res;
20     }
21 };
原文地址:https://www.cnblogs.com/habibah-chang/p/14402162.html