Permutation Sequence

Permutation Sequence

 Total Accepted: 6325 Total Submissions: 29550My Submissions

 

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

 

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

 

Have you been asked this question in an interview? 

假设有n个元素,第K个permutation是
a1, a2, a3, .....   ..., an
那么a1是哪一个数字呢?

那么这里,我们把a1去掉,那么剩下的permutation为
a2, a3, .... .... an, 共计n-1个元素。 n-1个元素共有(n-1)!组排列,那么这里就可以知道

设变量K1 = K
a1 = K1 / (n-1)!// 第一位的选择下标

同理,a2的值可以推导为

K2 = K1 % (n-1)!
a2 = K2 / (n-2)!

。。。。。

K(n-1) = K(n-2) /2!
a(n-1) = K(n-1) / 1!

an = K(n-1)

 

 

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         int data[]=new int[10];
 4         boolean visited[]=new boolean[10];
 5         data[0]=data[1]=1;
 6         ArrayList<Integer> list=new ArrayList<Integer>();
 7         for(int i=1;i<=n;i++)
 8         {
 9             data[i]=data[i-1]*(i);
10             list.add(i);
11         }
12         String result="";
13         k--;
14         for(int i=n-1;i>=0;i--)
15         {
16             int cur=k/data[i];
17             int j=1;
18             for(;j<9;j++)     //从数组中 针对未访问过的元素visited[]=false  找第cur个,找到的为j
19             {
20                 if(visited[j]==false)
21                     cur--;
22                 if(cur<0)
23                     break;
24             }
25             visited[j]=true;
26             result+=(j);
27             k=k%data[i];
28         }
29         return result;
30     }
31     
32 }

 

解二

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         int data[]=new int[n+1];
 4         boolean visited[]=new boolean[n+1];
 5         data[0]=data[1]=1;
 6         ArrayList<Integer> list=new ArrayList<Integer>();
 7         for(int i=1;i<=n;i++)
 8         {
 9             data[i]=data[i-1]*(i);
10             list.add(i);
11         }
12         String result="";
13         k--;
14         for(int i=n-1;i>=0;i--)
15         {
16             int cur=k/data[i];
17             result+=list.remove(cur);        //第cur个未正解,从list中删除
18             k=k%data[i];
19         }
20         return result;
21     }
22 }

 

 

基本思路就是

posted on 2014-04-20 19:13  wf110  阅读(1525)  评论(0编辑  收藏  举报