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

Leetcode 60. Permutation Sequence

时间:2017-03-22 23:04:25      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:blog   思路   clu   ++   class   unique   png   rem   ber   

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):

技术分享

Given n and k, return the kth permutation sequence.

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

标签 Backtracking Math

类似题目 (M) Next Permutation (M) Permutations

 
 
 
思路:
1.对于由{1,2,...,n}组成的第k个数(k从0开始),k = a * (n-1)! + b,其中a表示的是{1,2,...,n}中第a个数,b表示的是由{1,2,...,n}去掉第a个数后剩下的数(维持升序排列)构成的数组成的排列的第b个排列。
2.k = b,重复1共n次。

 

代码:

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         List<Integer> numbers = new ArrayList<>();
 4         int[] factor = new int[n];
 5         int i, t;
 6         String res = "";
 7         factor[0] = 1;
 8         for (i = 1; i < n; ++i)    factor[i] = factor[i - 1] * i;
 9         for (i = 1; i <= n; ++i) numbers.add(i);
10         k--;
11         for (i = n - 1; i >= 0 ; --i) {
12             t = k / factor[i];
13             res = res + numbers.get(t);
14             k = k % factor[i];
15             numbers.remove(t);
16         }
17         return res;
18     }
19 }

 

Leetcode 60. Permutation Sequence

标签:blog   思路   clu   ++   class   unique   png   rem   ber   

原文地址:http://www.cnblogs.com/Deribs4/p/6602289.html

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