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 閱讀(454) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 长寿区| 温泉县| 汶川县| 黎川县| 北安市| 迭部县| 呼和浩特市| 诸暨市| 津市市| 独山县| 恭城| 桐乡市| 图们市| 八宿县| 会东县| 莎车县| 泰和县| 临城县| 鞍山市| 靖宇县| 湖北省| 栾川县| 龙州县| 竹山县| 曲沃县| 洛扎县| 诸城市| 太白县| 通山县| 昌图县| 罗平县| 山东省| 定日县| 辽阳县| 潮州市| 云安县| 绵竹市| 毕节市| 古蔺县| 襄樊市| 靖西县|