I'm not sure I could write that even with a full day.

Even if I did, the solution would probably end up running in O(n!) time.