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.

这道题的规律性还是很强的,那就是n个数列中第一位的数字每个重复(n-1)!次,并按照从小到大的顺序出现,k/(n-1)!就是第一位要出现的数字,后边的依次类推。编程时要注意以下几个方面:一是原数列就是第一个数列,所以需要将k首先减1,其次是在求解过程中,需要将k落入当前位及其后所能表示的范围(所以需要对count取模),之后将count表示成当前位后边(不包括当前位)所能表示的范围(所以需要除以n-i),最后再求index时就是k除以count,这里边的主要思路就是当前位只能处理它所能处理的范围,超出当前范围的由其上级处理。另外就是每用掉一位,就将改为删除,并将其后位的数前移(数组始终保持递增数列)。

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int>num(n);
		int count = 1;
		string str;
		for(int i = 0; i < n; i++){
		    num[i] = i + 1;
			count *= num[i];
		}
		k--;				
		for(int i = 0; i < n; i++){			
			k = k % count;
			count /=(n - i);
		    int  index = k /count;
			char c = num[index] + '0';
			str.append(1,c);
			for(int j = index; j < n - 1; j++)
				num[j] = num[j + 1];			
		}
		return str;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值