O(n^2) method to permutation sequence problem