leetcode:数学:Permutation Sequence(060)

原创 2016年08月30日 15:11:56

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.


class Solution {
private:
    int getFactorial(int n) {
        int ret = n;
        while (--n)
            ret *= n;
        return ret;
    }

public:
    string getPermutation(int n, int k) {
        int fac = getFactorial(n);
        string candi = string("123456789").substr(0, n);
        string res(n, '0');
        for (int i = 0; i < n; i++) {
            fac /= (n - i);
            int index = (k - 1) / fac;
            res[i] = candi[index];
            candi.erase(index, 1);
            k -= index * fac;
        }
        return res;
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode060 Permutation Sequence

详细见:leetcode.com/problems/permutation-sequence Java Solution: github package leetcode; impo...
  • zxwtry
  • zxwtry
  • 2017年04月12日 21:08
  • 71

[C++]LeetCode: 114 Permutation Sequence(返回第k个阶乘序列——寻找数学规律)

题目: The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling ...

LeetCode | Permutation Sequence

题目: The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labelin...

leetcode: Permutation Sequence

这个题要求全排列的第几个。 首先我们知道,A(n,m)=n!/(n-m)

LeetCode89/60 Gray Code/Permutation Sequence--迭代

一:Leetcode 89 Gray Code 题目:The gray code is a binary numeral system where two successive values...

LeetCode-Permutation Sequence

public class Solution {     public String getPermutation(int n, int k) {         StringBuffer sb =...

Leetcode:Permutation Sequence

一:题目描述 The set[1,2,3,…,n]contains a total of n! unique permutations. By listing and labeling al...

【leetcode】【60】Permutation Sequence

一、问题描述 The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labe...

<LeetCode OJ> 60. Permutation Sequence

Total Accepted: 56468 Total Submissions: 221337 Difficulty: Medium The set [1,2,3,…,n] contains...

[leetcode]60. Permutation Sequence@Java解题报告

https://leetcode.com/problems/permutation-sequence/description/ The set [1,2,3,…,n] conta...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode:数学:Permutation Sequence(060)
举报原因:
原因补充:

(最多只允许输入30个字)