zoukankan      html  css  js  c++  java
  • LeetCode(60):Permutation Sequence

    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.

    题意:求由小于等于n的数字组成的数字,排序之后第k个的值。

    思路:参考博文

    代码:

    public class Solution {
        public String getPermutation(int n, int k) {
           
             int[] permutation = new int[n];
             permutation[0] = 1;
             for(int i=1;i<n;i++){
                 permutation[i] = permutation[i-1]*(i+1);
             }
             List<Integer> list = new LinkedList<Integer>();
             for(int i=1;i<=n;i++){
                 list.add(i);
             }
             StringBuilder sb = new StringBuilder();
             
            int pos = n-1;
            k-=1;
            while(pos>0){
                int index = k/permutation[pos - 1];
                sb.append(list.get(index));
                list.remove(index);
                k = k%permutation[pos-1];
                --pos;
            }
            sb.append(list.get(0));
            return sb.toString();
        }
    }
  • 相关阅读:
    WAMP Apache 2.5 配置虚拟主机
    DOM对象
    BOM对象
    JS内置对象
    CSS定位
    CSS浮动和清除
    浏览器兼容性
    垂直居中
    水平居中总结
    长度值
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5248311.html
Copyright © 2011-2022 走看看