One solution for all permutation

Time exceed