码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Permutation Sequence

时间:2016-05-31 06:31:18      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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-1)! ,下一位应该是(k%(n-1)!)/(n-2)!,以此类推。 

算法:

public String getPermutation(int n, int k) {  
        int nums[] = new int[n];  
        int pCount=1;  
        for(int i=0;i<nums.length;i++){  
            nums[i] = i+1;  
            pCount *= (i+1);//n!  
        }  
        k--;//下标从0开始  
        String res = "";  
        for(int i=0;i<n;i++){  
            pCount /=n-i;//(n-i-1)!  
              
            int r = k/pCount;  
            res+=nums[r];//第r小的元素  
            for(int j=r;j<n-1-i;j++){ //获取第r小的元素 所以将已经用过的元素覆盖    
                nums[j] = nums[j+1];  
            }  
            k = k%pCount;  
        }  
        return res;  
    }  


【Leetcode】Permutation Sequence

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51542413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!