• [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();
            
        }
    }
  • 相关阅读:
    Codeforces Round #398 (Div. 2) B,C
    KMP模板
    HDU1711 KMP(模板题)
    HDU3265 线段树(扫描线)
    HDU2795 线段树
    HDU1828线段树(扫描线)
    HDU1832 二维线段树求最值(模板)
    HDU1698 线段树(区间更新区间查询)
    HDU3251 最大流(最小割)
    cf2.c
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4642566.html
Copyright © 2020-2023  润新知