The current implementation works in exponential time in the worst case. I can easily avoid such a case by memorizing states.