The algorithm is same as https://code.google.com/p/perm/