LeetCode: 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.

利用nextPermutation。

class Solution {
public:
    void nextPermutation(vector<int> &num)
    {  
        int nSize = num.size();  
        if (nSize <= 1) return;  
          
        int idx = nSize - 1;  
        // 查找第一个下降的元素  
        while(--idx >= 0 && num[idx] >= num[idx+1]);  
        if (idx >= 0)  
        {  
            int i = nSize - 1;  
            // 查找第一个比idx所指元素大的元素  
            while(num[i] <= num[idx])  
            {  
                --i;  
            }  
            swap(num[i], num[idx]);  
            // 反转后面所有元素,让它从小到大sorted  
            reverse(num.begin()+idx+1, num.end());  
        }  
        else  
        {  
            reverse(num.begin(), num.end());  
        }  
    }  
    
    string getPermutation(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> num(n);
        for (int i = 1; i <= n; ++i)
            num[i-1] = i;;
            
        for (int i = 1; i < k; ++i)
            nextPermutation(num);
        
        string result;
        for (int i = 0; i < n; ++i)
            result += num[i] + '0';
        return result;
    }
};

你可能感兴趣的:(LeetCode: Permutation Sequence)