zoukankan      html  css  js  c++  java
  • [leedcode 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 (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.

    public class Solution {
        //本题思路:第n位确定时,会有(n-1)!个不同的排列组合。因此需要得到n!,
        //1.本题用count表示,每次循环时,count递减
        //2.需要构造一个LinkedList链表,之所以不使用数组而使用链表,是因为删除链表的一个节点时,链表会自动补充之前的空缺位,
        //如果是数组,每次remove都需要重新排列。
        //3.有一个细节,求第k位,首先k要减1,再进行计算
        
        //一、康托展开:全排列到一个自然数的双射
        //X=an*(n-1)!+an-1*(n-2)!+...+ai*(i-1)!+...+a2*1!+a1*0!
        //ai为整数,并且0<=ai<i(1<=i<=n)
        //适用范围:没有重复元素的全排列
        public String getPermutation(int n, int k) {
            StringBuilder seq=new StringBuilder();
            List<Integer> list=new LinkedList<Integer>();
            int count=1;
            for(int i=0;i<n;i++){
                list.add(i+1);
                count=count*(i+1);
            }
            k--;/////
            for(int i=0;i<n;i++){
                count=count/(n-i);
                int index=k/count;
                seq.append(list.get(index));
                list.remove(index);
                k=k%count;
                
            }
            return seq.toString();
            
        }
    }
  • 相关阅读:
    缓冲区
    4.9
    JDBC连接
    3.31
    BizTalk框架概述
    不通过SPS对象模型更改文档扩展字段的方法
    asdfasdf
    设计模式介绍
    Multiple Checkbox Items In A DataGrid Introduction
    Factory Method
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4642566.html
Copyright © 2011-2022 走看看