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(); } }