60. Permutation Sequence

来源:互联网 发布:免费的英语口语软件 编辑:程序博客网 时间:2024/06/05 07:06
public class Solution { public String getPermutation(int n, int k) { if(k>jiecheng(n) ||n<=0) return ""; boolean []visited=new boolean[n+1]; int i=1; String res=""; while(i<=n) { int temp=(k-1)/jiecheng(n-i)+1; //当前的第几个数 int count=0; for(int j=1;j<=n;j++) { if(!visited[j]) { count++; } if(count==temp) //未被访问过的第几个数 { visited[j]=true; res+=String.valueOf(j); break; } } k=(k-1)%jiecheng(n-i)+1; i++; } return res; } public int jiecheng(int n) { if(n==0) return 1; //0的阶乘等于1. int res=1; while(n>0) { res*=n; n--; } return res; }}
0 0