Simple JAVA Solution


  • 0
    K

    public class Solution {

    /**
     * 1.  1234
     * 2.  1243
     * 3.  1324
     * 4.  1342
     * 5.  1423
     * 6.  1432
     * 
     * 7.  2134
     * 8.  2143
     * 9.  2314
     * 10. 2341
     * 11. 2413
     * 12. 2431
     * 
     * 13. 3124
     * 14. 3142
     * 15. 3214
     * 16. 3241
     * 17. 3412
     * 18. 3421
     * 
     * 19. 4123
     * 20. 4132
     * 21. 4213
     * 22. 4231
     * 23. 4312
     * 24. 4321
     */
    
    public String getPermutation(int n, int k) {
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            list.add(i);
        }
        
        StringBuilder builder = new StringBuilder();
        
        long fac = getFac(n);
        while (n > 0) {
            fac /= n;
            int next = (int) ((long) (k - 1) / fac) + 1;
            int nextDigit = list.get(next - 1);
            
            builder.append(nextDigit);
            k = (int) ((long) (k - 1) % fac) + 1;
            n--;
            
            list.remove(new Integer(nextDigit));
        }
        return builder.toString();
    }
    
    private long getFac(int n) {
        long fac = 1;
        while (n > 1) {
            fac *= n--;
        }
        return fac;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.