60. Permutation Sequence

道理我都懂,但是还是调了n久,写出来发现哪哪都没问题,最后发现是k没有--

都是泪

 

 1     public String getPermutation(int n, int k) {
 2         if(n == 0 || k == 0) {
 3             return "";
 4         }
 5         k--;
 6         List<Integer> digits = new ArrayList<Integer>();
 7         for(int i = 1; i <= n; i++) {
 8             digits.add(i);
 9         }
10         StringBuilder sb = new StringBuilder();
11         int fac = factory(n-1);
12         for(int i = n - 1; i > 0; i--) {
13             int current = k / fac;
14             k %= fac;
15             sb.append(digits.get(current));
16             digits.remove(current);
17             fac /= i;
18         }
19         sb.append(digits.get(0));
20         return sb.toString();
21     }
22     
23     private static int factory(int n) {
24         int sum = 1;
25         for(int i = 1; i <= n; i++) {
26             sum *= i;
27         }
28         return sum;
29     }

Kkkkkkk提前减一!!!

posted @ 2016-03-05 09:19  warmland  阅读(125)  评论(0编辑  收藏  举报