AC java solution


  • 0
    Q
    public String getPermutation(int n, int k) {
        boolean[] isUsed = new boolean[n];
        StringBuffer sb = new StringBuffer();
        
        int numsLeft = n;
        for(int i = 0 ; i < n ; i++){
            if(numsLeft > 1){
                int mThUnused = (k-1)/factorial(numsLeft-1);
                int counter = -1;
                int head = 0;
                
                for( ;head< n && counter<mThUnused ; head++){
                    if(!isUsed[head])
                        counter++;
                }
                
                isUsed[head-1] = true;
                sb.append(head);
                k= k - mThUnused*factorial(numsLeft-1);
                numsLeft--;
            }
            else
                for(int j = 0 ; j < n ; j++)
                    if(!isUsed[j]){
                        sb.append(j+1);
                        break;
                    }
        }
        
        return sb.toString();
    }
    
    private int factorial(int n) {
        int fact = 1; // this  will be the result
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }

Log in to reply
 

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