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

“123”
“132”
“213”
“231”
“312”
“321”
Given n and k, return the kth permutation sequence.

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

思路1:利用STL里面的next_permutation()函数找下一个排列;

string getPermutation(int n, int k) {
    if (k == 0)return "";
    ostringstream out;
    for (int i = 1; i <= n; i++)out << i;
    string str = out.str();
    if (k == 1)return str;
    int count = 1;
    do{
        if (count == k)break;
        count++;
    } while (next_permutation(str.begin(), str.end()));
    return str;
}

思路2:因为上一种方法虽然可以AC,但是只有6.*%,感觉应该有更高效的算法存在;
假设有四位数字{1, 2, 3, 4},那么他们能够产生的排列数是什么呢?

1 + {2, 3, 4}
2 + {1, 3, 4}
3 + {1, 2, 4}
4 + {1, 2, 3}

其实就是选定第一位数字以后,其他剩下的数字进行排列组合,就能求出该数字打头的所有排列组合。想必已经能发现一些规律了,我们干脆再举一个具体的例子,比如我们现在想要找第14个数,那么由于14 = 6 + 6 + 2。因此第一个数打头的是3,然后再求{1, 2, 4}中第二个排列组合数,答案是”142”。所以最终答案就是”3142”啦。

还有一些问题需要注意:
1. 构造排列数从最高位开始,当选出一个数字后,就把该数字erase掉,防止后面又出现;
2. 我们所要求得第K个数小每次从循环中减去对应的值;
3. 注意程序中数组时从0开始的,但题目输入是从1开始计数的;

string getPermutation(int n, int k) {
    vector<int> perm(n + 1, 1);
    for (int i = 1; i <= n; i++)perm[i] = perm[i - 1] * i;

    vector<char> digits = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    int num = n - 1;
    string res;
    while (num){
        int t = (k - 1) / perm[num--];
        k = k - t * perm[num + 1];
        res.push_back(digits[t]);
        digits.erase(digits.begin() + t);
    }
    res.push_back(digits[k - 1]);
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值