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 sequenc...

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.

 

参考:http://www.cnblogs.com/tenosdoit/p/3721918.html

 

C++实现代码:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

class Solution {
public:
    string getPermutation(int n, int k) {
        if(n==0)
            return "";
        int total=factorial(n);
        string str=string("123456789").substr(0,n);
        string ret(n,' ');
        int i;
        for(i=0;i<n;i++)
        {
            int index;
            total=total/(n-i);
            index=(k-1)/total;
            ret[i]=str[index];
            str.erase(index,1);
            k=k-index*total;
        }
        return ret;
    }

    int factorial(int n)
    {
        if(n==0)
            return 0;
        int i;
        int sum=1;
        for(i=1;i<=n;i++)
           sum*=i;
        return sum;
    }
};

int main()
{
    Solution s;
    cout<<s.getPermutation(3,5)<<endl;
}

 

相关文章
LeetCode 60. Permutation Sequence
集合[1,2,3,...,n]总共包含n的阶乘个独特的排列。
52 0
LeetCode 60. Permutation Sequence
|
算法
LeetCode 128. Longest Consecutive Sequence
给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。
63 0
LeetCode 128. Longest Consecutive Sequence
LeetCode 357. Count Numbers with Unique Digits
给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10n 。
61 0
LeetCode 357. Count Numbers with Unique Digits
|
算法 C#
算法题丨Longest Consecutive Sequence
描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
1089 0
1085. Perfect Sequence (25)
#include #include #include using namespace std; int main() { int n; long p; cin >> n >> p; v...
837 0
|
人工智能 机器学习/深度学习
1007. Maximum Subsequence Sum (25)
简析:求最大子列和,并输出其首末元素。在线处理,关键在于求首末元素。 本题囧,16年9月做出来过,现在15分钟只能拿到22分,有一个测试点过不了。
948 0