Java Solution, easy to understand.


  • 0
    public class Solution {
    // 1. get n! and store 1->n as a list
    // 2. regular pattern:
    //    current number index= k/(n-1)!;
    //    k=k%(n-1)%
    // 3. remember to remove the selected number from the num list
    public String getPermutation(int n, int k) {
        int m=1;
        List<Integer> nums=new ArrayList<Integer>();
        for(int i=1;i<=n;i++){
            m=m*i;
            nums.add(i);
        }
        k--;
        StringBuilder sb=new StringBuilder();
        int i=n,mod=m;
        while(nums.size()!=0){
            mod=mod/i;
            int index=k/mod;
            sb.append(nums.get(index));
            nums.remove(index);
            k=k%mod;
            i--;
            
        }
        return sb.toString();
    }
    

    }


Log in to reply
 

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