码迷,mamicode.com
首页 > 其他好文 > 详细

60. Permutation Sequence

时间:2017-04-26 10:08:18      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:rem   integer   dex   string   存在   get   blog   tco   关系   

题目:

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.

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

标签:rem   integer   dex   string   存在   get   blog   tco   关系   

原文地址:http://www.cnblogs.com/panini/p/6766741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!