leetcode之Permutation Sequence
来源:互联网 发布:everyone piano mac 编辑:程序博客网 时间:2024/05/21 19:25
原题如下:
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.
这道题的规律性还是很强的,那就是n个数列中第一位的数字每个重复(n-1)!次,并按照从小到大的顺序出现,k/(n-1)!就是第一位要出现的数字,后边的依次类推。编程时要注意以下几个方面:一是原数列就是第一个数列,所以需要将k首先减1,其次是在求解过程中,需要将k落入当前位及其后所能表示的范围(所以需要对count取模),之后将count表示成当前位后边(不包括当前位)所能表示的范围(所以需要除以n-i),最后再求index时就是k除以count,这里边的主要思路就是当前位只能处理它所能处理的范围,超出当前范围的由其上级处理。另外就是每用掉一位,就将改为删除,并将其后位的数前移(数组始终保持递增数列)。class Solution {public: string getPermutation(int n, int k) { vector<int>num(n);int count = 1;string str;for(int i = 0; i < n; i++){ num[i] = i + 1;count *= num[i];}k--;for(int i = 0; i < n; i++){k = k % count;count /=(n - i); int index = k /count;char c = num[index] + '0';str.append(1,c);for(int j = index; j < n - 1; j++)num[j] = num[j + 1];}return str; }};
0 0
- leetcode之Permutation Sequence
- leetcode 之 Permutation Sequence
- LeetCode之Permutation Sequence
- leetcode之Permutation Sequence
- 【Leetcode】之Permutation Sequence
- leetcode之Permutation Sequence解题思路
- LeetCode OJ 之 Permutation Sequence (排列组合)
- LeetCode第60题之Permutation Sequence
- LeetCode进阶之路(Permutation Sequence)
- LeetCode: Permutation Sequence
- LeetCode Permutation Sequence
- [Leetcode] Permutation Sequence
- [LeetCode] Permutation Sequence
- leetcode 74: Permutation Sequence
- leetcode Permutation Sequence
- [leetcode] Permutation Sequence
- [LeetCode]Permutation Sequence
- LeetCode:Permutation Sequence
- WWDC2014开源代码
- java-j2ee环境的搭建
- 插入排序
- 《定位》书摘
- 各开源框架使用与设计总结(一)
- leetcode之Permutation Sequence
- CSDN登录绑定整的太操蛋了!
- 网站里加入百度地图。
- java/JDK配置环境变量
- 高斯分布抽样
- 很关键共和国恢复
- 将 Shiro 作为应用的权限基础 三:基于注解实现的授权认证过程
- MAC下打Android 多渠道 带签名APK包。
- 从输入 URL 到页面加载完成的过程中都发生了什么事情?