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

    Solution:

     1 public class Solution {
     2     public String getPermutation(int n, int k) {
     3         if(n==1&&k==1)
     4             return "1";
     5         int total=getTotal(n);
     6         String original=getOriginal(n);
     7         char[] result=new char[n];
     8         for(int i=0;i<n;++i){
     9             total/=(n-i);
    10             int t2=(k-1)/total;
    11             result[i]=original.charAt(t2);
    12             original=original.replace(result[i]+"", "");  //这个方法很巧妙啊,用此法就可以把用过的数字从数组里去掉了!!!
    13             k-=t2*total;                                  
    14         }
    15         return new String(result);
    16     }
    17 
    18     private String getOriginal(int n) {
    19         // TODO Auto-generated method stub
    20         String result="";
    21         for(int i=1;i<=n;++i){
    22             result+=i+"";
    23         }
    24         return result;
    25     }
    26 
    27     private int getTotal(int n) {
    28         // TODO Auto-generated method stub
    29         int total=1;
    30         for(int i=1;i<=n;++i){
    31             total*=i;
    32         }
    33         return total;
    34     }
    35 }
  • 相关阅读:
    软件工程
    ROR
    全息技术(Holographic technique)
    VR技术、AR技术、MR技术
    人工智能(AI)
    机器学习(Machine Learning)
    hdoj Scaena Felix
    周赛题解
    Good Luck in CET-4 Everybody!(博弈)
    Paths on a Grid(规律)
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4097599.html
Copyright © 2011-2022 走看看