IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
          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):
          "123"
          "132"
          "213"
          "231"
          "312"
          "321"
          Given n and k, return the kth permutation sequence.
          Note: Given n will be between 1 and 9 inclusive.

          這道題其實有很強的規律可循。首先,n個元素的排列總數是n!。在下面的分析中,讓k的范圍是0 <= k < n!。(題目代碼實際上是1<=k<=n!)
          可以看到一個規律,就是這n!個排列中,第一位的元素總是(n-1)!一組出現的,也就說如果p = k / (n-1)!,那么排列的最開始一個元素一定是arr[p]。
          這個規律可以類推下去,在剩余的n-1個元素中逐漸挑選出第二個,第三個,...,到第n個元素。程序就結束。
           1 /**
           2  * The set [1,2,3,…,n] contains a total of n! unique permutations.
           3  * 
           4  * By listing and labeling all of the permutations in order, We get the
           5  * following sequence (ie, for n = 3):
           6  * 
           7  * "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation
           8  * sequence.
           9  * 
          10  * Note: Given n will be between 1 and 9 inclusive.
          11  * 
          12  */
          13 
          14 public class PermutationSequence {
          15     public String getPermutation(int n, int k) {
          16         char[] arr = new char[n];
          17         int pro = 1;
          18         for (int i = 0; i < n; ++i) {
          19             arr[i] = (char) ('1' + i);
          20             pro *= (i + 1);
          21         }
          22         k = k - 1;
          23         k %= pro;
          24         pro /= n;
          25         for (int i = 0; i < n - 1; ++i) {
          26             int selectI = k / pro;
          27             k = k % pro;
          28             pro /= (n - i - 1);
          29             int temp = arr[selectI + i];
          30             for (int j = selectI; j > 0; --j) {
          31                 arr[i + j] = arr[i + j - 1];
          32             }
          33             arr[i] = (char) temp;
          34         }
          35         return String.valueOf(arr);
          36     }
          37 }
          38 
          posted on 2014-01-07 16:06 Meng Lee 閱讀(452) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 长治县| 西乡县| 平舆县| 冀州市| 阿合奇县| 古浪县| 鄂州市| 榕江县| 尉犁县| 利津县| 新蔡县| 沐川县| 鲁甸县| 大姚县| 甘谷县| 沧源| 伊吾县| 铜陵市| 闻喜县| 桓台县| 合肥市| 鄂温| 罗城| 察隅县| 元阳县| 涟水县| 博客| 平利县| 易门县| 沭阳县| 临夏县| 保康县| 大名县| 武宣县| 连山| 鄂托克旗| 玉林市| 西乡县| 禄劝| 牟定县| 临泽县|