leetcode 60. Permutation Sequence

leetcode 60. Permutation Sequence

//"123"
//"132"
//"213"
//"231"
//"312"
//"321"

//2413

//12
//21

/*
A用来记录每位有多少种排列组合
B用来记录当前有多少可用数字

下面是用递归方式实现的,递归肯定更好理解。

当拿到n个数字的第k个排列时,先计算第一位是什么数字。后面的n-1个数字有 A[n-1]种组合,也就是说顺序是这样的
1  XXX A[n-1]种
2  XXX A[n-1]种
...
n  XXX A[n-1]种

k/A[n-1]就是首位字母了,用过的字母从B中去掉,后面就完全相同了。


*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int A[] = { 0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
char BB[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };

class Solution {
public:
    string getPermutation(int n, int k) {
        this->N = n;
        B = string(BB, BB + n);
        k = k - 1;//?0??
        return recursion(n, k);
    }
    string recursion(int n, int k){
        if (n == 1){
            return string{ getNotUsed(0) };
        }
        int div = A[n - 1];
        int a = k / div, b = k % div;
        string left{ getNotUsed(a) };
        return left + recursion(n - 1, b);
    }
    char getNotUsed(int leftNum){
        int SIZE = B.size();
        leftNum %= SIZE;
        char tmp = B[leftNum];
        B.erase(begin(B) + leftNum);
        return tmp;
    }
private:
    int N;
    string B;
};

int main()
{
    for (int i = 1; i <= 6;i++)
    cout << Solution().getPermutation(3, i) << endl;
    system("pause");
}

posted @ 2017-12-04 14:35  开学五年级了  阅读(112)  评论(0编辑  收藏  举报