Added a better algorithm (in cpp).

Pruning many recursion calls.