[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.

思考:模拟肯定超时。参考:http://www.abcoding.info/?p=805 。注意string的几个函数用法。

class Solution {

public:

    string getPermutation(int n, int k) {

		int d[10],i;

		d[1]=1;

		for(i=2;i<=9;i++) d[i]=d[i-1]*i;

		k--;

		string ans,s;

		for(i=1;i<=9;i++) s.append(1,i+'0');

		for(i=n-1;i>=0;i--)

		{

			int temp=k/d[i];

			k=k%d[i];

			ans.append(1,s[temp]);

			s.erase(temp,1);

		}

		return ans;

    }

};

  

你可能感兴趣的:(LeetCode)