LeetCode_OJ【60】Permutation Sequence
2016-02-20 11:06
369 查看
The set
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.
这道题目的思路比较简单,但是在写的时候还是有一些细节要注意。
第K个数在sequenc中的序号为k-1。n-1个数的全排列个数为(n-1)!,(k-1)/(n-1)!得到的就是String中第一个数字在set中的位置。
比如此题中给定输入n =3,k = 5。(k-1)/(n-1)! =2,而set中序号为2的数字是3。由此思路可以一直求下去得到结果。
public String getPermutation(int n, int k) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> fact = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i ++){
list.add(i+1);
if(i == 0 || i == 1)
fact.add(1);
else
fact.add(fact.get(i-1)*i);
}
String res ="";
k--;
while(n > 0){
res += list.remove(k/fact.get(n-1));
k = k % fact.get(n-1);
n--;
}
return res;
}
[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.
这道题目的思路比较简单,但是在写的时候还是有一些细节要注意。
第K个数在sequenc中的序号为k-1。n-1个数的全排列个数为(n-1)!,(k-1)/(n-1)!得到的就是String中第一个数字在set中的位置。
比如此题中给定输入n =3,k = 5。(k-1)/(n-1)! =2,而set中序号为2的数字是3。由此思路可以一直求下去得到结果。
public String getPermutation(int n, int k) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> fact = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i ++){
list.add(i+1);
if(i == 0 || i == 1)
fact.add(1);
else
fact.add(fact.get(i-1)*i);
}
String res ="";
k--;
while(n > 0){
res += list.remove(k/fact.get(n-1));
k = k % fact.get(n-1);
n--;
}
return res;
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解