Javascript solution, short and beats 86.67%


  • 1
    E
    var getPermutation = function(n, k) {
        var ns=[]
            ,res=[]
            ,pos=k-1;
        for (var i=1;i<=n;++i) { ns.push(i); }
        var nfac=ns.reduce((prev,curr)=>prev*curr);
        if (k<1||k>nfac) { return "error"; }
        for (var j=n;j>=1;--j) {
            nfac/=j;
            res.push(ns.splice(parseInt(pos/nfac),1)[0]);
            pos%=nfac;
        }
        return res.join("");
    };

Log in to reply
 

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