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 閱讀(451) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 北安市| 甘谷县| 扎赉特旗| 彰化县| 巴彦县| 梧州市| 吉安县| 咸阳市| 肃北| 南宫市| 钟祥市| 荔波县| 女性| 秦皇岛市| 卢湾区| 宁国市| 盱眙县| 临朐县| 莆田市| 伊金霍洛旗| 宜兰县| 北票市| 香河县| 苍溪县| 松溪县| 廊坊市| 溆浦县| 达拉特旗| 丰宁| 星子县| 乌兰县| 泰宁县| 新龙县| 长白| 正镶白旗| 海阳市| 罗定市| 米脂县| 科尔| 卢湾区| 太和县|