设为首页 加入收藏

TOP

Leetcode--Permutation Sequence
2015-07-20 17:47:15 来源: 作者: 【 】 浏览:2
Tags:Leetcode--Permutation Sequence

Problem Description:

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个排列,提交之后会超时,在网上搜索之后发现可以直接构造出第k个排列,以n = 4,k = 17为例,数组src = [1,2,3,...,n]。

    第17个排列的第一个数是什么呢:我们知道以某个数固定开头的排列个数 = (n-1)! = 3! = 6, 即以1和2开头的排列总共6*2 = 12个,12 < 17, 因此第17个排列的第一个数不可能是1或者2,6*3 > 17, 因此第17个排列的第一个数是3。即第17个排列的第一个数是原数组(原数组递增有序)的第m = upper(17/6) = 3(upper表示向上取整)个数。

    第一个数固定后,我们从src数组中删除该数,那么就相当于在当前src的基础上求第k - (m-1)*(n-1)! = 17 - 2*6 = 5个排列,因此可以递归的求解该问题。

    代码实现中注意一个小细节,就是一开始把k--,目的是让下标从0开始,这样下标就是从0到n-1,不用考虑n时去取余,更好地跟数组下标匹配。具体代码如下:

    class Solution {
    public:
    
    	int fun(int n)
    	{
    		if(n<0)
    			return 0;
    		else if(n==0)
    			return 1;
    		else
    			return n*fun(n-1);
    	}
    
    	string getPermutation(int n, int k) {
    		string s;
    		int total=fun(n);
    		if(total
        
          flag(n,0);
    		//因为数组是从0到n-1的,所以基数从0到k-1  
    		--k;
    		for(int i=0;i
         
          


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU1055 POJ2054 Color a Tree 下一篇NYOJ-取石子(六)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)