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 for n = 3:

"123"
"132"
"213"
"231"
"312"
"321"

Given n and k, return the kth permutation sequence.

Note:

Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"

难度:medium

题目:集合[1, 2, 3, …. n]包含n!个不同的排列。有序的列出所有排列

给定n和k, 返回第k个序列。

思路:结合next_permutation。此方法非简单方法。

Runtime: 31 ms, faster than 16.21% of Java online submissions for Permutation Sequence.

Memory Usage: 37.6 MB, less than 6.50% of Java online submissions for Permutation Sequence.

class Solution {
    public String getPermutation(int n, int k) {
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = i + 1;
        }
        for (int i = 0; i < k - 1; i++) {
            nextPermutation(nums);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append(nums[i]);
        }
        
        return sb.toString();
    }
    
    public void nextPermutation(int[] nums) {
        if (null == nums || nums.length <= 1) {
            return;
        }
        int right = nums.length - 1, j = right;
        for (; j > 0; j--){
            if (nums[j - 1] < nums[j]) break;
        }
        for (int k = right; k >= 0; k--) {
            if (j > 0 && nums[k] > nums[j - 1]) {
                swap(nums, j - 1, k);
                break;
            }
        }
        for (; j < right; j++, right--) {
            swap(nums, j, right);
        }
    }
    
    private void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}

原文 

https://segmentfault.com/a/1190000018132038

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 60. Permutation Sequence

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址