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.


这种方法超时了。

char A[1000];
class Solution {
    
public:

void perm(int i , int n , int k,int & count , string &s , bool tag){
		if(tag)
			return;
		if(i == n){
		    count ++;
			if(count == k){
				tag = true;
				s=A;
				return;
			}			
		}
		for(int j = i ; j < n ; j ++){
			swap(A[i],A[j]);
			perm(i + 1 , n , k , count , s,tag);
			swap(A[i],A[j]);
			if(tag)
				break;
		}
	}
    
      string getPermutation(int n, int k) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        for(int i = 0 ; i< n ; i ++)
		{
			A[i] = (char)(i + '1');
		}
		string s;
		int count = 0;
		bool tag = false;
		perm(0,n,k,count ,s,tag);
		return s;

    }
};

重写之后的算法过了


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