60. Permutation Sequence
来源:互联网 发布:研如寓 知乎 编辑:程序博客网 时间:2024/06/05 20:34
String ret = ""; int k; public String getPermutation(int n, int k) { this.k = k - 1;//第k个字符串表示变化了k - 1次 int[] alphabet = new int[n];//存储还有哪些数字可选 for (int i = 1;i <= n;i++)//初始化数字表 alphabet[i - 1] = i; recursive(alphabet,n); return ret; } public void recursive(int[] alphabet,int n){//n表示正在计算第n位的值 if (n == 0) return;//递归必须设置结束点 int factorial = factorial(n - 1); int quotient = k / factorial;//求出商看它在倒数第i位变了几次 k %= factorial; ret += String.valueOf(alphabet[quotient]); int[] newAlphabet = new int[n - 1]; for (int i = 0,j = 0;i < n;i++)//生成新的数字表,不包含原数字表里已经用过的数字 if (i != quotient) { newAlphabet[j] = alphabet[i]; j++; } recursive(newAlphabet,n - 1); } public int factorial(int x){//求阶乘的函数 if (x == 0) return 1; int factorial = x; while (x > 1){ factorial *= --x; } return factorial; }
原题:
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.
即给定int n,int k。返回第k个n的全排列(按递增形式排列)所形成的数字串。
思考过程:
一开始意识到这个和阶乘相关,但是思路并不清晰。后来意识到比如n = 5,k = 120,是从12345往上变化了119次。变化4! * 4次后是51234,也就是从右往左数的第n为取决于
k / (n - 1)!,其中k每次都更新为k % (n - 1)!。采用递归的算法,用一个数组存储还剩下的数字(递增顺序),然后每次递归更新k值和字母表。详情见代码注释。
AC代码:
阅读全文
1 0
- LeetCode --- 60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60.Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- **LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- [LeetCode]60. Permutation Sequence
- LeetCode *** 60. Permutation Sequence
- 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- hiho 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- PHP-Warning: mkdir() [function.mkdir]: Permission denied……问题解决
- X code及Main.storyboard 基本使用
- C/C++ memset详解
- js--事件对象
- facebook数据爬取
- 60. Permutation Sequence
- 手机端html5触屏事件(touch事件)3
- 基于时间的反向传播算法BPTT(Backpropagation through time)
- css技巧--进阶
- Windows下使用taskkill命令批量结束进程
- android studio 配置 opencv for android
- AndroidExported receiver does not require permission.
- 容器Response详解
- windows CMD 命令下dir 命令