标签:
题目:
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):
"123"
"132"
"213"
"231"
"312"
"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)); } }
LeetCode - Permutation Sequence
标签:
原文地址:http://www.cnblogs.com/shuaiwhu/p/5080251.html