60. Permutation Sequence

栏目: Java · 发布时间: 6年前

内容简介: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:Given n and k, return the kth 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;
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

阿里巴巴正传:我们与马云的“一步之遥”

阿里巴巴正传:我们与马云的“一步之遥”

方兴东、刘伟 / 江苏凤凰文艺出版社 / 2015-1 / 45.00

十几年来,方兴东与马云每年一次,老友聚首,开怀畅谈,阿里上市前,作者再次与马云深度对话,阿里上市前的布局,深入探讨了一系列人们关心的话题。 本书忠实记录了阿里壮大、马云封圣的历史。作者通过细致梳理和盘点,对阿里巴巴的15年成长史进行了忠实回顾。从海博翻译社到淘宝网,从淘宝商城到天猫,从支付宝到阿里云计算,从拉来软银的第一笔投资到纽交所上市,作者对其中涉及到的人物、细节都有生动展现;对于马云、......一起来看看 《阿里巴巴正传:我们与马云的“一步之遥”》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

html转js在线工具
html转js在线工具

html转js在线工具