leetcode 60. 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 {
	set<string>re;
	void select_one(vector<pair<string, vector<int>>>&candis)
	{
		vector<pair<string, vector<int>>>newcandi;
		re.clear();
		for (int i = 0; i < candis.size(); i++)
		{
			for (int j = 0; j < candis[i].second.size(); j++)
			{
				string pp = candis[i].first;
				pp += '0' + candis[i].second[j];
				if (candis[i].second.size() == 1)
					re.insert(pp);
				else
				{
					vector<int>remain = candis[i].second;
					remain.erase(remain.begin() + j, remain.begin() + j + 1);
					newcandi.push_back(pair<string, vector<int>>(pp, remain));
				}
			}
		}
		candis = newcandi;
	}
public:
	string getPermutation(int n, int k) {
		vector<int>nums;
		for (int i = 0; i < n; i++)
			nums.push_back(i + 1);
		int jj = n;
		vector<pair<string, vector<int>>>candi;
		candi.push_back(pair<string, vector<int>>(string(""), nums));
		while (jj-- >= 1)
		{
			select_one(candi);
		}
		int i = 1;
		for (set<string>::iterator it = re.begin(); it != re.end(); it++, i++)
			if (i == k)
				return *it;
	}
};

试试9,慢的吓人,坑定不能用这种方法。

换一种方法


class Solution {
	long long int factorial(int n)
	{
		long long int re = 1;
		for (int i = 1; i <= n; i++)
			re *= i;
		return re;
	}
public:
	string getPermutation(int n, int k) {
		if (n == 1 && k == 1)
			return string("1");
		vector<int>nums;
		for (int i = 0; i < n; i++)
			nums.push_back(i + 1);
		int jj = n;
		string re;
		while (true)
		{
			int index = (k-1) / (factorial(jj - 1));
			k = k-factorial(jj - 1)*index;
			re += '0' + nums[index];
			nums.erase(nums.begin()+index, nums.begin()+index+1);
			jj--;
			if (jj == 1)
			{
				re += ('0' + nums[0]);
				return re;
			}
		}
	}
};


accepted



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值