Leetcode NO.60 Permutation Sequence
来源:互联网 发布:电脑语音同声翻译软件 编辑:程序博客网 时间:2024/06/06 02:36
题目要求如下:
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.
算法的思路如下:1,定义一个map存储 1到 n这n个值。C++ 的STL map是根据key大小排序的
2,要高清排序规则,就拿题干中的例子举例:
比如第三位213,如果从零开始排位,它就是k = k - 1 =2;
2.1 k / (n-1)! = 2 / 2 = 1, map里面有三个key 1,2,3选择序号是1的即2,然后删除此值, k = k % (n-1)! = 0
2.2 0 / (n-2)! = 0 / 1 = 0, map里面有两个key 1,3选择序号是0的即1,然后删除此值,k = k % (n-2)! = 0
2.3 只剩一个值,就是3.
213为最终解,
代码如下:
class Solution {public: string getPermutation(int n, int k) { string retVal = ""; map<int, int> num_map; map<int, int>::iterator it; for (int i = 1; i <= n; ++i) num_map[i] = i; int tmp_n = n - 1; k = k - 1; while (tmp_n >= 0) { int tmp = k / factorial(tmp_n); k = k % factorial(tmp_n); for (it = num_map.begin(); it != num_map.end(); ++it) { if (tmp == 0){ retVal += to_string(it->first); num_map.erase(it); break; } else --tmp; } --tmp_n; } return retVal; }private:int factorial(int n) {int result = 1;for (int i = 1; i <= n; ++i)result *= i;return result;}};
0 0
- Leetcode NO.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
- LeetCode 60: Permutation Sequence
- LeetCode 60 Permutation Sequence
- 【Leetcode】Permutation Sequence(60)
- Leetcode 60 Permutation Sequence
- leetcode-60-Permutation Sequence
- 数据库篇之存储过程[bsp_getfavoriteproductlist](非官方版本)
- 数据库篇之存储过程[bsp_createorder](非官方版本)
- 数据库篇之最后几个数据表的更新
- AsyncTask 并行任务使用、测试
- [LeetCode] Surrounded Regions, Solution
- Leetcode NO.60 Permutation Sequence
- 排序算法(一)- 冒泡排序
- 排序算法(二)- 快速排序
- 安装 CentOS 7 后必做的七件事
- Step by Step Ubuntu下GPU测试Theano
- Leetcode NO.50 Pow(x, n)
- 使用nat123来用外网访问内网SVN-https443映射方法
- asp.net,jsp,php,安卓Android,ios计算机毕业课程设计源码免费打包下载
- Xsolla对话成都游戏茶馆CEO