<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 評(píng)論 :: 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.

    這道題其實(shí)有很強(qiáng)的規(guī)律可循。首先,n個(gè)元素的排列總數(shù)是n!。在下面的分析中,讓k的范圍是0 <= k < n!。(題目代碼實(shí)際上是1<=k<=n!)
    可以看到一個(gè)規(guī)律,就是這n!個(gè)排列中,第一位的元素總是(n-1)!一組出現(xiàn)的,也就說如果p = k / (n-1)!,那么排列的最開始一個(gè)元素一定是arr[p]。
    這個(gè)規(guī)律可以類推下去,在剩余的n-1個(gè)元素中逐漸挑選出第二個(gè),第三個(gè),...,到第n個(gè)元素。程序就結(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 閱讀(452) 評(píng)論(0)  編輯  收藏 所屬分類: Leetcode
    主站蜘蛛池模板: 国产精品网站在线观看免费传媒| 亚洲精品97久久中文字幕无码| 免费人成激情视频在线观看冫 | 好猛好深好爽好硬免费视频| 亚洲中文字幕久久精品蜜桃 | 最近的2019免费中文字幕| 亚洲色少妇熟女11p| 99久久精品国产亚洲| 亚洲尤码不卡AV麻豆| 亚洲成A人片77777国产| 成年丰满熟妇午夜免费视频 | 亚洲av成人一区二区三区| 久久国产亚洲精品麻豆| 亚洲欧洲中文日韩av乱码| 国产大片91精品免费观看男同| 成人免费午夜无码视频| 222www免费视频| 久久精品私人影院免费看| 高清永久免费观看| 日韩a毛片免费观看| 国产亚洲精品91| 色窝窝亚洲AV网在线观看| 亚洲乱码在线观看| 亚洲AV无码一区二区三区人| 亚洲国产精品网站久久| 亚洲特级aaaaaa毛片| 亚洲视频在线观看不卡| 亚洲色图在线观看| 精品亚洲A∨无码一区二区三区| 亚洲成年轻人电影网站www | 最近免费2019中文字幕大全| 久久这里只精品99re免费| 免费无码VA一区二区三区| 小日子的在线观看免费| 午夜视频在线免费观看| 日韩免费无码一区二区三区| ww4545四虎永久免费地址| 国产精品久久免费| 全免费a级毛片免费看无码| 日本黄页网站免费| 亚洲成a人一区二区三区|