zoukankan      html  css  js  c++  java
  • Java for LeetCode 060 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.

    解题思路:

    之前曾在Java for LeetCode 046 PermutationsJava for LeetCode 031 Next Permutation做过关于字典排序的算法,但是可以肯定,这种近乎暴力枚举的算法肯定是通不过测试的!通过观察发现k / factorial(n - 1)其实就代表了str的第一个字母,顺着这个思路以此类推即可,JAVA实现如下:

    	static public String getPermutation(int n, int k) {
    		StringBuilder str = new StringBuilder();
    		for (int i = 0; i < n; i++)
    			str.append(i + 1);
    		StringBuilder sb = new StringBuilder();
    		while (n > 1) {
    			int index = k / factorial(n - 1);
    			k %= factorial(n - 1);
    			if(k==0){
    				index--;
    				sb.append(str.charAt(index));
    				str.deleteCharAt(index);
    				sb.append(new StringBuilder(str).reverse());
    				return sb.toString();
    			}
    			sb.append(str.charAt(index));
    			str.deleteCharAt(index);
    			n--;
    		}
    		return "1";
    	}
    	
    	static int factorial(int n) {
    		if (n == 1)
    			return 1;
    		else
    			return (factorial(n - 1) * n);
    	}
    
  • 相关阅读:
    MySQL 5.5版本数据库介绍与二进制安装
    nginx配置文件的基础优化
    yum源是什么
    微服务之间调用token管理
    微服务之间调用事务处理
    idea
    sentry
    infinispan配置
    微服务事务处理
    高并发处理
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4506818.html
Copyright © 2011-2022 走看看