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);
	}

 

posted @ 2015-05-15 20:43  TonyLuis  阅读(135)  评论(0编辑  收藏  举报