【Leetcode】Permutation Sequence(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.

看到此题,立马想到了暴力,直接搜。但是已提交发现超时了。想了很久,没有办法就找找题解喽。看到题解当时就懂了,做法简单粗暴,但是很有效果。(也是看了别人的题解,然后自己写一下,加深一下印象)。全排列可以分为n个组,每个组的第一位是1~n。每组有(n-1)!个全排列(相当于第二位到最后一位的全排),于是k/(n-1)!就可以得到需要的排列的第一位nums[k/(n-1)!]。然后把该位去掉,后面的数字向前移动,计算第二位时k为k%(n-1)!。以此类推,得到结果。

string int_string(int n){
	stringstream ss;
	string si;
	ss << n;
	ss >> si;
	return si;
}

string getPermutation(int n, int k) {
	int m;
	map<int, string> map_ss;
	int pcount = 1;
	for (m =0; m <n; m++){
	  map_ss[m] = int_string(m+1);
	  pcount *= (m + 1);
	}
	int i;
	int num = 0;
	k--;
	string s="";
	for (i = 0; i < n; i++){
		pcount /= (n - i);
		int selected = k / pcount;
		s += map_ss[selected];
		k = k%pcount;
		int j = selected;
		for (; j < n-i-1; j++){
			map_ss[j] = map_ss[j + 1];
		}
	}
	return s;
}
用到了一个int转string,以前写过 c++ int 类型与string类型的相互转化

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值