Fork me on GitHub

【LeetCode】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):

  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.

提示:

这道题我一上来使用了backtracking的方法依次构造出排列数,当然结果不出所料的TLE了。实际上,仔细观察这些数字,我们还是不难发现一些规律的。

假设有四位数字{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"啦。

这里有一些问题是需要我们注意的:

  • 构造排列数从最高位开始,当选出一个数字后,就应当把这个数字erase掉,防止后面又出现;
  • 我们所要求的第k个数需要在每次循环中减去对应的值;
  • 注意程序中的数组是从0开始的,但题目的输入是从1开始计数的。

代码:

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> permutation(n + 1, 1);
        for (int i = 1; i <= n; ++i) {
            permutation[i] = permutation[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) / (permutation[num--]);
            k = k - t * permutation[num + 1];
            res.push_back(digits[t]);
            digits.erase(digits.begin() + t);
        }
        res.push_back(digits[k - 1]);
        return res;
    }
};

 

posted @ 2016-03-22 10:41  __Neo  阅读(2365)  评论(0编辑  收藏  举报