60. Permutation Sequence
Posted panini
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了60. 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):
"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.
链接: http://leetcode.com/problems/permutation-sequence/
4/25/2017
17ms, 60%
一开始的思路是对的,但是没有想到k如果递减到下一层。并且也没有想到用链表来存。每一步都是把之前的变成了更小的排列。
注意,这道题其实与n可以没有关系,输入只要是没有重复的数组就可以了,长度是n
是不是存在第k个这种更一般的算法呢?
算法是抄的。注意第9行不需要变为string,将int加到sb中自动转为了char???
1 public class Solution { 2 public String getPermutation(int n, int k) { 3 if (n <= 0) return ""; 4 List<Integer> list = new LinkedList<Integer>(); 5 StringBuilder sb = new StringBuilder(); 6 int factorials = 1; 7 8 for (int i = 1; i <= n; i++) { 9 list.add(i); 10 factorials *= i; 11 } 12 13 k -= 1; // used k for the list index 14 while (n > 0) { 15 factorials /= n; 16 sb.append(list.remove(k / factorials)); 17 k %= factorials; 18 n--; 19 } 20 return sb.toString(); 21 } 22 }
别人的算法,大同小异
区别是factorials他用数组表示
https://discuss.leetcode.com/topic/17348/explain-like-i-m-five-java-solution-in-o-n
https://discuss.leetcode.com/topic/5081/an-iterative-solution-for-reference
更多讨论:
https://discuss.leetcode.com/category/68/permutation-sequence
以上是关于60. Permutation Sequence的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode(60):Permutation Sequence
LeetCode31 Next Permutation and LeetCode60 Permutation Sequence