Ah, I see. Forgive me for not noticing that earlier; I assumed the method did something else.
The problem lies in that I don't think there's a clever way to solve this problem; you need to check *all* combinations, and then choose the smallest one. You unfortunantly found a clever way to find a a solution has a higher probability of being correct, but not a way to find the correct solution.
As I mentioned earlier, I think this is an
NP-Complete problem, but I lack the background in discrete mathematics to say it with authority.
The good news is you can stop trying to be clever and do it the brute force way. If you
do come up with a better solution, let me know. It's an interesting problem.