leetcode-60. Permutation Sequence
2016-12-09 09:59
316 查看
leetcode-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.
这题的思路试这样的
首先你要判断第一个排列是多少?比如3排列,那他开头的选择有3种,每种有两个,推广来说就是对于n排列,第一个数有n中选择,每种选择的数量是(n-1)!个排列数量。
然后在判断第二个,依次类推。
但是这里还有一个问题需要解释一下。就是为什么要建list然后把1-n的数按顺序插入进去,这个时机上是判断还有那些数待排序。例如你要判断3排列的第4个数,在第一位的时候将2插入进去,这样队列就是剩1和3。判断第二位的时候将3插入进去这样队列就是剩1。
public class Solution { public String getPermutation(int n, int k) { StringBuilder sb = new StringBuilder(); List<Integer> list = new ArrayList<Integer>(); for(int i = 1;i <= n ; i++){ list.add(i); } helper(sb,n,k,list); return sb.toString(); } private void helper(StringBuilder sb,int n,int k,List<Integer> list){ if(k==0 || list.isEmpty()){ for(int i : list) sb.append(i); return; } int step = 1; for(int i = n-1;i>1;i--){ step*=i; } int pos = (k-1)/step; k -= step * pos; // System.out.println(n+" "+k+" "+pos+" "+step); sb.append(""+list.get(pos)); list.remove(pos); helper(sb,n-1,k,list); } }
相关文章推荐
- 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 找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
- leetcode60. Permutation Sequence
- leetcode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- Leetcode--60. Permutation Sequence
- LeetCode 60. Permutation Sequence