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();
        }
    }
  • 相关阅读:
    蜘蛛禁止访问文件
    基于PhalApi的Smarty拓展 (视图层的应用)
    MySQL数据库存表情
    查看PHP版本等相关信息
    读取数据库表信息
    nginx简介
    Redis发布订阅
    Redis持久化
    Redis主从复制
    Redis的Java客户端Jedis
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5248311.html
Copyright © 2011-2022 走看看