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     }
  • 相关阅读:
    抽象
    数据处理—异常值处理
    数据处理—数据连续属性离散化
    数据处理—缺失值处理
    数据处理—归一化
    数据特征—正态性检验
    数据特征—相关性分析
    数据分析—统计分析
    数据特征—帕累托分析
    特征分析—对比分析
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3423937.html
Copyright © 2011-2022 走看看