Leetcode刷题记—— 60. Permutation Sequence(排列序列)
来源:互联网 发布:淘宝网薄印花半大开衫 编辑:程序博客网 时间:2024/06/05 17:20
一、题目叙述:
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.
Subscribe to see which companies asked this question.
二、解题思路:
Medium题。进步了,好像50%多了
思路:
例如 n=3, k=4,首先计算第一个字符应该是几,因为每个字符在第一位的排列数为sum=!(n - 1)个,排列序x = k -1;所以用sum/x=(k-1)/!(n-1)计算出是,第几个数字,如此时(4-1)/!(3-1)= 1 ,所以第一位应该是第一大的数(还有第0大的数)即2;接下来计算第二位上的数,同理,通过取余得到此时的排列序x值 :x=(k-1)%!(n-1),除以此时的排列数sum=!(n-1-1),得到第二位上数应为剩下数中第1大的数即3,以此类推,直到n个字符都加进字符串为止。
(1)创建一个list,把‘1’到‘n’的字符放进去。
(2)计算排列次序x,计算排列数sum,相除得到此时应将剩下数字中的第几大数字加入字符串(加入后将list中的该字符删除),更新相关参数;直到将全部n个字符加入字符串。
三、源码:
import java.util.ArrayList;import java.util.Arrays;public class Solution { public String getPermutation(int n, int k) {ArrayList<Character> temp = new ArrayList<Character>(); String a = ""; for (int i = 0; i < n; i++) temp.add((char)('1' + i)); int x = k - 1; while (temp.size() > 1) { int sum = 1; for (int j = 1; j < n; j++) sum *= j; n--; a = a + temp.get(x / sum); temp.remove(x / sum); x = x % sum; } a += temp.get(0); return a; } public static void main(String args[]) { int[] nums = {1,1,2}; //String word = "ABfS"; Solution solution = new Solution(); System.out.print(solution.getPermutation(5, 72)); } }
- Leetcode刷题记—— 60. Permutation Sequence(排列序列)
- LeetCode 60. Permutation Sequence(排列序列)
- Permutation Sequence 排列序列
- Permutation Sequence 求第k个的排列序列 @LeetCode
- 数据结构与算法[LeetCode]—Permutation Sequence 求n个数的全排列中第K个序列
- leetCode 60.Permutation Sequence (排列序列) 解题思路和方法
- LeetCode | 60. Permutation Sequence——第K个全排列
- LeetCode——60. Permutation Sequence
- LeetCode——Permutation Sequence
- Leetcode刷题记—— 46. Permutations(排列)
- leetcode 60. Permutation Sequence 第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
- 第一次上linux课
- Problem--282A--Codeforces--BIt++
- Eclipse在线安装 报错 An error occurred while collecting items to be installed
- 缓慢渐变维度 (Slowly Changing Dimension) 常见的三种类型及原型设计
- To solve machine learning problems
- Leetcode刷题记—— 60. Permutation Sequence(排列序列)
- 面试(Java)
- 原子变量&&CAS算法
- MySQL二进制日志格式对复制的影响
- 浅谈散列
- 转成数组的通用函数
- Nginx静态资源简单配置
- 20170304-java
- LeapMotion驱动安装教程