LeetCode Permutation Sequence

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) {
    	vector<int> digits;
		for(int i = 1; i <= n; ++i)
			digits.push_back(i);
		for(int i= 1; i < k; ++i)
			nnext_permutation(digits);
		stringstream oss;
		for(int i = 0; i < digits.size(); ++i)
			oss << digits[i];
		return oss.str();
    }

	void nnext_permutation(vector<int>& digits)
	{
		int first = digits.size() - 1;
		while(--first >= 0 && digits[first] >= digits[first+1]);
		if(first >= 0)
		{
			int second = digits.size();
			while(--second >= 0 && digits[second] <= digits[first]);

			swap(digits[first], digits[second]);
			reverse(digits.begin()+first+1, digits.end());
		}
		else
		{
			reverse(digits.begin(), digits.end());
		}
	}
};



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