60. Permutation Sequence

Base on next permutation:

class Solution {
    public String getPermutation(int n, int k) {
        char[] arr=new char[n];
        for(int i=0;i<n;i++)
            arr[i]=(char)('1'+i);
        for(int i=1;i<k;i++)
            nextPermutation(arr);
        return new String(arr);
    }
    private void nextPermutation(char[] arr)
    {
        int idx=arr.length-1;
        while(idx>0&&arr[idx]<=arr[idx-1])
            idx--;
        if(idx==0)
            Arrays.sort(arr);
        else
        {
            int i=idx-1;
            int j=arr.length-1;
            while(arr[i]>=arr[j])
                j--;
            char tmp=arr[i];
            arr[i]=arr[j];
            arr[j]=tmp;
            
            i=idx;
            j=arr.length-1;
            while(i<j)
            {
                tmp=arr[i];
                arr[i]=arr[j];
                arr[j]=tmp;
                i++;
                j--;
            }
        }
    }
}

 

class Solution {
    public String getPermutation(int n, int k) {
        LinkedList<Integer> list=new LinkedList<Integer>();
        int fact=1;
        for(int i=1;i<=n;i++)
        {
            list.add(i);
            fact*=i;
        }
        
        StringBuilder sb=new StringBuilder();
        k=(k-1)%fact;
        while(n>0)
        {
            fact/=n;
            int idx=k/fact;
            sb.append(list.get(idx));
            list.remove(idx);
            k=k%fact;
            n--;
        }
        return sb.toString();
    }
}

 

posted @ 2017-09-26 03:56  Weiyu Wang  阅读(134)  评论(0编辑  收藏  举报