思路:这道题目还是很有意思的,统计情况,如果要遍历情况的话可以用回溯法,不过超时是必然的,我们可以用数学的思路来分析这个问题:
分析:abc必须按照顺序排列才能满足我们的情况,所以,我们从后往前考虑,不做任何的推理,光凭逻辑我们应该可以知道,当str[i] = ‘c’的时候,此时字符串的排列情况,应该与i之前的c出现的次数,以及b有关;同样的我们可以知道在i之前的j当str[j] = ‘b’的时候,此时字符串的排列情况,应该与j之前的b出现的次数,以及a有关;
而单单只分析a出现的次数的话,即假设str形式如(aaa…aaabc)这种情况,那么此时最后统计的结果应该是2^a_count(a出现的次数)-1,等价于从前往后遍历字符串a_count = a_count*2+1;
然后我们就可以知道,b_count = a_count + b_count*2;
然后c_count = b_count+c_count*2
而最后的结果就是c_count;
ps:说了这么一大堆,我自己也被绕糊涂了,文笔有限,还请见谅
class Solution {
public:
/*
* @param : the input string
* @return: the number of subsequences
*/
int countSubsequences(string &source) {
// write your code here
int a_count = 0, b_count = 0, c_count = 0;
for(auto x : source)
{
if(x == 'a')
a_count = 1 + 2*a_count;
else if (x == 'b')
b_count = a_count + 2*b_count;
else if(x == 'c')
c_count = b_count + 2*c_count;
}
return c_count;
}
};