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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        N = n;
        int jc = get_jiecheng(n-1);
        K = (k-1) % jc +1;
        start = (k-1) / jc;
        cnt = 0;
        record = vector<int>(N, 0); 
        result.clear();
        got.clear();
        trace_back(n, start);
        return result;
    }
    
    void trace_back(int n, int start) {
        
        if (cnt > K) {
            return;
        }
        
        if (0 == n) {
            ++cnt;
            if (cnt == K) {
                result = got;
            }
            return;
        }
                
        for (int i = start; i < N; ++i) {
            if (0 == record[i]) {
                got.push_back('1'+ i);
                record[i] = 1;
                trace_back(n - 1, 0);
                got.pop_back();
                record[i] = 0;
            }
        }
    }
    
    int get_jiecheng(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * get_jiecheng(n - 1); 
        }
    }
    
    int K;
    int N;
    int start;
    int cnt;
    string got;
    vector<int> record;
    string result;
};


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