For example, let the string be the first 10 digits of pi, 3141592653
, and the subsequence be 123
. Note that the sequence occurs twice:
psh. O(n) solutions are way better.
Think of it by building a tree:
iterate along the string if the character is '1', add a node to the the root of the tree. if the character is '2', add a child to each first level node. if the character is '3', add a child to each second level node.
return the number of third layer nodes.
this would be space inefficient so why don't we just store the number of nodes a each depth:
infile >> in;
long results[3] = {0};
for(int i = 0; i < in.length(); ++i) {
switch(in[i]) {
case '1':
results[0]++;
break;
case '2':
results[1]+=results[0];
break;
case '3':
results[2]+=results[1];
break;
default:;
}
}
cout << results[2] << endl;