leetcode 60. Permutation Sequence
2017-07-04 20:25
405 查看
The set
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.
按字典序全排列组合,求第k个组合是什么
思路是,对每一个数求它在这个排列中的顺序是怎么的,从而得到这一个位置的数字
public class Solution {
public String getPermutation(int n, int k) {
k--;
StringBuilder sb = new StringBuilder();
int factorial = 1;
for(int i = 2; i < n; i++)
factorial *= i;
List<Integer> numList = new ArrayList<Integer>();
for(int i = 1; i<= n; i++){
numList.add(i);
}
int times = n-1;
while(times>=0){
int index = k/factorial;
sb.append(numList.get(index));
numList.remove(index);
k = k%factorial;
if(times!=0)
factorial = factorial/times;
times--;
}
return sb.toString();
}
}
[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.
按字典序全排列组合,求第k个组合是什么
思路是,对每一个数求它在这个排列中的顺序是怎么的,从而得到这一个位置的数字
public class Solution {
public String getPermutation(int n, int k) {
k--;
StringBuilder sb = new StringBuilder();
int factorial = 1;
for(int i = 2; i < n; i++)
factorial *= i;
List<Integer> numList = new ArrayList<Integer>();
for(int i = 1; i<= n; i++){
numList.add(i);
}
int times = n-1;
while(times>=0){
int index = k/factorial;
sb.append(numList.get(index));
numList.remove(index);
k = k%factorial;
if(times!=0)
factorial = factorial/times;
times--;
}
return sb.toString();
}
}
相关文章推荐
- LeetCode-60. Permutation Sequence
- Leetcode #60. Permutation Sequence 排列组合序列 解题报告
- Leetcode 60. Permutation Sequence (Medium) (cpp)
- [LeetCode]60. Permutation Sequence
- 个人记录-LeetCode 60. Permutation Sequence
- LeetCode --- 60. Permutation Sequence
- leetcode_60. Permutation Sequence 找n的全排列中的第k个序列
- Leetcode 60. Permutation Sequence
- leetcode: 60. Permutation Sequence
- LEETCODE 60. Permutation Sequence
- 【一天一道LeetCode】#60. Permutation Sequence.
- [LeetCode] 60. Permutation Sequence
- [LeetCode]60. Permutation Sequence
- LeetCode *** 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- 【一天一道LeetCode】#60. Permutation Sequence.
- Leetcode:60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- [LeetCode] 60. Permutation Sequence 序列排序