LeetCode 60. Permutation Sequence(N排列,第K序列)

题目描述:

    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,2,3,…,n]包含 n! 种不同的排列。给定 (19) 和 k,返回第k个字典序排列。

LeetCode 60

    思路:如上图所示,这是一道经典的数学题。我们举个栗子说明:假设n = 3,k = 3,则共存在N = n! = 3! = 6种排列,为了取值方便,我们构造字符串str = "123...n" = "123"。那么如果k值大于6时,其实进入了循环状态(7→1、8→2、9→3、...),此时进行取模操作kk = (k - 1) % N + 1 = 3。n = 3说明每个排列都是3位数,我们先计算它的首位数字。首位数字有3种可能,因此后两位数字有N = N / i = 6 / 3 = 2(i∈{3,2,1},分别代表第(4 - i)位数字有i种可能)种可能。那么首位数字在str种的位置cnt = (kk - 1) / N = 2 / 2 = 1,即首位数字 = "2"。此时后两位剩余kk = kk - cnt * N = 3 - 1 * 2 = 1种可能排列,str更新为str = "13"(因为"2"已经使用)。
    对于i∈{3,2,1},重复以上步骤,获得ans = "213"。
    时间复杂度为O(n)。

代码:

#include <bits/stdc++.h>

using namespace std;

// Note: Given n will be between 1 and 9 inclusive.
class Solution {
public:
    string getPermutation(int n, int k) {
		// Exceptional Case: 
        if(n == 1){
			return "1";
		}
		string str = "";
		// get n!
		int N = 1;
		for(int i = 2; i <= n; i++){
			N *= i;
		}
		// get "1234...n"
		for(int i = 1; i <= n; i++){
			str += (i + '0');
		}
		string ans = "";
		// check if k > N
		int kk = (k - 1) % N + 1;
		for(int i = n; i >= 1; i--){
			N /= i;
			int cnt = (kk - 1) / N;
			ans += str[cnt];
			kk -= cnt * N;
			str.erase(cnt, 1);
		}
		return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值