1. 程式人生 > >第k個排列

第k個排列

blog tin 排列 logs eof div math nbsp public

給定 nk,求123..n組成的排列中的第 k 個排列。

註意事項

1 ≤ n ≤ 9

樣例

對於 n = 3, 所有的排列如下:

123
132
213
231
312
321

如果 k = 4, 第4個排列為,231.

 1 public class PaiLieK
 2 {
 3     public String getPermutation(int n, int k)
 4     {
 5         List<Integer> list = new ArrayList<>();
6 List<Integer> list1 = new ArrayList<>(); 7 for(int i = 1; i <= n; i++) 8 { 9 list.add(i); 10 } 11 12 boolean has = true; 13 first: 14 for(int i = 0; i < Math.pow(10,n);i++) 15 { 16 for
(int j = 0; j < list.size(); j++) 17 { 18 if(!(i+"").contains(list.get(j)+"")) 19 { 20 has = false; 21 continue ; 22 } 23 } 24 if(has&&list.size() == getDigits(i))
25 { 26 list1.add(i); 27 } 28 has = true; 29 } 30 Integer integer=list1.get(k-1); 31 return String.valueOf(integer); 32 } 33 34 35 public int getDigits(int i) 36 { 37 int count = 0; 38 while(i >0) 39 { 40 count++; 41 i /=10; 42 } 43 return count; 44 } 45 @Test 46 public void testGetDigits() 47 { 48 System.out.println(getDigits(198)); 49 getDigits(198); 50 } 51 @Test 52 public void testGetPermutation() 53 { 54 String permutation = getPermutation(3, 4); 55 System.out.println(permutation); 56 } 57 58 }

第k個排列