您的位置:首页 > 产品设计 > UI/UE

60. Permutation Sequence

2016-06-27 11:06 417 查看
题目:

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.

Note: Given n will be between 1 and 9 inclusive.

题意:

这道题的意思是顺序找出1~n的第k个排列组合,并返回。

思路:

给定数字为4,则集合为{1、2、3、4}。将所有序列全部罗列出来如下所示:

1 + (permutations of 2, 3, 4) 

2 + (permutations of 1, 3, 4) 

3 + (permutations of 1, 2, 4) 

4 + (permutations of 1, 2, 3)

给定数字为n,则所有的序列总数为n!个组合,比如上面,当有3个数字得时候一共有6(3!)种序列,意味着4个数字总共有24(4*3!)种组合。所以如果想要找到(k=14)第14个序列,则该序列一定在3 + (permutations of 1, 2, 4) 子集中。程序实现时,k=13(减1是因为一般的数组下标从0开始的),在数组{1、2、3、4}中,k/(n-1)!
= 13/(4-1)! = 13/3! = 13/6 = 2.在数组{1、2、3、4}中下标为2的数组值为3,所以第一个数字为3,之后的操作按照上一次的实现规则重复。。。
代码:Time
Limit Exceeded

public class Solution {
    public String getPermutation(int n, int k) {
        int pos = 0;
        List<Integer> numbers = new ArrayList<>();
        int[] factorial = new int[n+1];
        StringBuilder sb = new StringBuilder();
    
        //存储阶乘值 factorial[] = {1, 1, 2, 6, 24, ... n!}
        int sum = 1;
        factorial[0] = 1;
        for(int i=1; i<=n; i++){
            sum *= i;
            factorial[i] = sum;
        }
    
        //存储数字集 numbers = {1, 2, 3, 4}
        for(int i=1; i<=n; i++){
            numbers.add(i);
        }
    
        k--; //找到数组对应下标 14=>13
    
        for(int i = 1; i <= n; i++){
            int index = k/factorial[n-i];
            sb.append(String.valueOf(numbers.get(index)));
            numbers.remove(index);
            k -= index*factorial[n-i];
        }
    
        return String.valueOf(sb);
    }
}
代码:java版:3ms
public class Solution {
    public String getPermutation(int n, int k) {
        LinkedList<Integer> list = new LinkedList<>();
        for (int i = 1; i <= n; i++) list.add(i); //存储数字集 numbers = {1, 2, 3, 4}
        
        int fact = 1;
        for (int i = 2; i <= n; i++) fact *= i; // 最大阶乘值
    
        StringBuilder strBuilder = new StringBuilder();
        for (k--; n > 0; n--) {
            fact /= n;  //(n-1)!
            strBuilder.append(list.remove(k / fact));
            k %= fact;
        }
    
        return strBuilder.toString();
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: