leetcode之Permutation Sequence

来源:互联网 发布:everyone piano mac 编辑:程序博客网 时间:2024/05/21 19:25

原题如下:

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.

这道题的规律性还是很强的,那就是n个数列中第一位的数字每个重复(n-1)!次,并按照从小到大的顺序出现,k/(n-1)!就是第一位要出现的数字,后边的依次类推。编程时要注意以下几个方面:一是原数列就是第一个数列,所以需要将k首先减1,其次是在求解过程中,需要将k落入当前位及其后所能表示的范围(所以需要对count取模),之后将count表示成当前位后边(不包括当前位)所能表示的范围(所以需要除以n-i),最后再求index时就是k除以count,这里边的主要思路就是当前位只能处理它所能处理的范围,超出当前范围的由其上级处理。另外就是每用掉一位,就将改为删除,并将其后位的数前移(数组始终保持递增数列)。

class Solution {public:    string getPermutation(int n, int k) {        vector<int>num(n);int count = 1;string str;for(int i = 0; i < n; i++){    num[i] = i + 1;count *= num[i];}k--;for(int i = 0; i < n; i++){k = k % count;count /=(n - i);    int  index = k /count;char c = num[index] + '0';str.append(1,c);for(int j = index; j < n - 1; j++)num[j] = num[j + 1];}return str;    }};


0 0