zoukankan      html  css  js  c++  java
  • Permutation Sequence

    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):

    1. "123"
    2. "132"
    3. "213"
    4. "231"
    5. "312"
    6. "321"

    Given n and k, return the kth permutation sequence.

    Note: Given n will be between 1 and 9 inclusive.

    代码:

     1     string getPermutation(int n, int k) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int fac[10];
     5         fac[0] = 1;
     6         for(int i = 1; i <= 9; i++){
     7             fac[i] = fac[i-1]*i;
     8         }
     9         string result = "";
    10         vector<int> nums;
    11         for(int i = 0; i < n; i++)
    12             nums.push_back(i+1);
    13         for(int i = n; i >= 1; i--){
    14             if(k <= fac[i-1]){
    15                 result += (nums[0]+'0');
    16                 nums.erase(nums.begin());
    17             }
    18             else if(k == fac[i]){
    19                 for(vector<int>::iterator it = nums.end()-1; it >= nums.begin(); it--){
    20                     result += (*it+'0');
    21                 }
    22                 break;
    23             }
    24             else{
    25                 int j = (k-1)/fac[i-1]+1;
    26                 k = k - (j-1)*fac[i-1];
    27                 vector<int>::iterator it = nums.begin();
    28                 while(j > 1){
    29                     it++;
    30                     j--;
    31                 }
    32                 result += (*it+'0');
    33                 nums.erase(it);
    34             }
    35         }
    36         return result;
    37     }
  • 相关阅读:
    jvm09
    jvm08
    jvm07
    求解最长公共子序列问题
    归并排序
    求解N皇后问题
    快速排序算法
    求解0/1背包问题
    求解全排列问题
    求解最大连续子序列和问题
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3423937.html
Copyright © 2011-2022 走看看