60. Permutation Sequence

来源:互联网 发布:成龙女儿知乎 编辑:程序博客网 时间:2024/06/05 09:27

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;}
原创粉丝点击