<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    IT技術(shù)小屋

    秋風(fēng)秋雨,皆入我心

      BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
      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.

    這道題其實有很強的規(guī)律可循。首先,n個元素的排列總數(shù)是n!。在下面的分析中,讓k的范圍是0 <= k < n!。(題目代碼實際上是1<=k<=n!)
    可以看到一個規(guī)律,就是這n!個排列中,第一位的元素總是(n-1)!一組出現(xiàn)的,也就說如果p = k / (n-1)!,那么排列的最開始一個元素一定是arr[p]。
    這個規(guī)律可以類推下去,在剩余的n-1個元素中逐漸挑選出第二個,第三個,...,到第n個元素。程序就結(jié)束。
     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 閱讀(450) 評論(0)  編輯  收藏 所屬分類: Leetcode
    主站蜘蛛池模板: 亚洲中文字幕久久精品无码VA| 免费一级特黄特色大片在线| 亚洲AV永久无码精品成人| 丰满少妇作爱视频免费观看| vvvv99日韩精品亚洲| 丰满亚洲大尺度无码无码专线 | 成年私人影院免费视频网站| 亚洲第一成年网站大全亚洲| 97视频免费观看2区| 亚洲天堂中文字幕| 222www免费视频| 亚洲人成网站看在线播放| 毛片高清视频在线看免费观看| 亚洲中文字幕无码中文| 国产成人免费全部网站| 成人嫩草影院免费观看| 国产精品亚洲一区二区三区在线| 久久爰www免费人成| 亚洲乱人伦精品图片| 成年人免费网站在线观看| 日本系列1页亚洲系列| 亚洲视频在线精品| 久久免费看少妇高潮V片特黄| 亚洲性色成人av天堂| 午夜视频在线观看免费完整版| 国产区图片区小说区亚洲区| 亚洲中文字幕久久精品无码APP| 精品国产免费一区二区三区香蕉| 亚洲日本在线观看网址| 国产成人免费ā片在线观看| 中文字幕乱理片免费完整的| 久久精品国产亚洲av水果派| 午夜免费福利在线| 免费无码又爽又刺激网站| 亚洲伊人久久大香线蕉啊| 国产极品美女高潮抽搐免费网站| 三级毛片在线免费观看| youjizz亚洲| 综合亚洲伊人午夜网 | 人妻仑乱A级毛片免费看| 99亚洲精品高清一二区|