LeetCode 060 Permutation Sequence

来源:互联网 发布:steam 在mac上打不开 编辑:程序博客网 时间:2024/05/22 10:31

题目描述

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.

分析

首先想到的是递归,按照顺序寻找字符串,然后计数,计算到第k个就是所求字符串。但是这样太慢,在n=9,k很大时会超时。

然后根据规律来,我们发现当n=3时排列是3! = 6组,其中以“1”,“2”,“3”开头的分别有2组。

以“1”开头的排列中,第2位是“2”、“3”的分别有1组。

如果n=4呢?会发现以1开头的排列有6组,其中以2为第2位的排列有2组。

总结规律:第一位数字在数组中的序号肯定是:

k1/(n1)!

k1=k

第二位数字在剩余数组中的序号肯定是:

k2/(n2)!

k2=k1

以此类推。

代码

    public static String getPermutation(int n, int k) {        if (n <= 0 || k <= 0) {            return "";        }        String result = "";        List<Integer> list = new ArrayList<Integer>();        int fact = 1;        for (int i = 1; i <= n; i++) {            list.add(i);            fact *= i;        }        k--;        for (int i = 0; i < n; i++) {            fact /= (n - i);            int index = k / fact;            result += list.get(index);            list.remove(index);            k %= fact;        }        return result;    }

代码 超时

    int kth;    int count;    String result;    public String getPermutation(int n, int k) {        if (n <= 0 || k <= 0) {            return "";        }        kth = k;        count = 0;        dfs("", n);        return result;    }    void dfs(String s, int n) {        if (s.length() == n) {            if (++count == kth) {                result = s;            }            return;        }        if (count > kth) {            return;        }        for (int i = 1; i <= n; i++) {            if (!s.contains(i + "")) {                dfs(s + i, n);            }        }    }
0 0
原创粉丝点击