Leetcode算法学习日志-60 Permutation Sequence

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.

题意分析

寻找按字典排序的第k个序列。

解法分析

对于一个n,可以构建n的所有排列的排列树,树的叶子数代表总的排列数,共n!个,对于第一层的n个子树,每个子树包含(n-1)!个序列,通过k与(n-1)!的取商取余,可以逐步寻找到相应解,c++代码如下:

class Solution {
private:
	int N;//total path in each layer
	int curPath;
	int K;//the order in each layer

public:
	int pathNumber(int layer) {
		int i;
		curPath = 1;
		for (i = 1; i <= (N - layer); i++) {
			curPath = curPath*i;
		}
		int temp = K / (curPath / (N - layer));
		if (K % (curPath / (N - layer)) == 0) {
			K = curPath / (N - layer);
			return temp - 1;
		}
		else {
			K = K % (curPath / (N - layer));
			return temp;
		}

	}
	string getPermutation(int n, int k) {
		N = n;
		K = k ;
		string res;
		vector<int> num;
		int i;
		for (i = 1; i <= n; i++) {
			num.push_back(i);
		}
		if (n == 1)
			return "1";
		int whichWay;
		for (i = 0; i<n; i++) {
			whichWay = pathNumber(i);
			res.push_back('0'+num[whichWay]);
			num.erase(num.begin() + whichWay);
		}
		//res.push_back(num[0]);
		return res;
	}
};




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值