leetcode 60. Permutation Sequence

来源:互联网 发布:mc9s12xs128单片机实验 编辑:程序博客网 时间:2024/06/13 20:58

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.

思路在于 缩小范围

class Solution {public:    string getPermutation(int n, int k)     {        if (n == 1)            return "1";        vector<int> m1;        string result;        int p = 1;          //记录一共有多少种        for(int i=1;i<=n;i++)        {               p = p * i;            m1.push_back(i);        }              for(int i = n; i > 0; i--)        {                  p = p / i;                              //以马上找到的这一位后面有多少种情况            result = result + char(m1[(k-1)/p] + 48);             m1.erase(m1.begin() + (k - 1) / p);     //把插入过的删除            k = k - (k-1)/p * p;         }        return result;    }};


原创粉丝点击