zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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.

    思路:

    除法和求余运算,对每一组数往下递推

    package permutation;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class PermutationSequence {
    
        public String getPermutation(int n, int k) {
            List<Integer> l = new ArrayList<Integer>();
            for (int i = 1; i <= n; ++i) 
                l.add(i);
            --k;
            StringBuilder sb = new StringBuilder();
            for (int i = n; i > 0; --i) {
                int fib = fib(i - 1);
                int index = k / fib;
                k = k % fib;
                sb.append((char)('0' + l.get(index)));
                l.remove(index);
            }
            return sb.toString();
        }
        
        private int fib(int n) {
            int res = 1;
            for (int i = 1; i <= n; ++i)
                res *= i;
            return res;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            PermutationSequence p = new PermutationSequence();
            System.out.println(p.getPermutation(4, 5));
        }
    
    }
  • 相关阅读:
    crypto 密码加密
    -webkit-box 高度自动填满
    performance数据
    AJAX
    Javascript sort方法
    Javascript reduce方法
    如何让div内的多行文本上下左右居中
    js基础
    for循环的执行顺序
    json对象和json字符串
  • 原文地址:https://www.cnblogs.com/null00/p/5080251.html
Copyright © 2011-2022 走看看