Leetcode NO.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.

算法的思路如下:

1,定义一个map存储 1到 n这n个值。C++ 的STL map是根据key大小排序的

2,要高清排序规则,就拿题干中的例子举例:

比如第三位213,如果从零开始排位,它就是k = k - 1 =2;

2.1 k / (n-1)! = 2 / 2 = 1, map里面有三个key 1,2,3选择序号是1的即2,然后删除此值, k = k % (n-1)! = 0

2.2 0 / (n-2)! = 0 / 1 = 0, map里面有两个key 1,3选择序号是0的即1,然后删除此值,k = k % (n-2)! = 0

2.3 只剩一个值,就是3.

213为最终解,

代码如下:

class Solution {
public:
    string getPermutation(int n, int k) {
    	string retVal = "";

        map<int, int> num_map;
        map<int, int>::iterator it;
        for (int i = 1; i <= n; ++i)
        	num_map[i] = i;
        int tmp_n = n - 1;
        k = k - 1;
        while (tmp_n >= 0) {
        	int tmp = k / factorial(tmp_n);
        	k = k % factorial(tmp_n);
        	for (it = num_map.begin(); it != num_map.end(); ++it) {
        		if (tmp == 0){
        			retVal += to_string(it->first);
        			num_map.erase(it);
        			break;
        		}
        		else
        			--tmp;
        	}
        	--tmp_n;
        }
        return retVal;
    }

private:
	int factorial(int n) {
		int result = 1;
		for (int i = 1; i <= n; ++i)
			result *= i;
		return result;
	}
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值