Leetcode_permutation-sequence(c++ and python version)
来源:互联网 发布:知豆电动汽车电池质保 编辑:程序博客网 时间:2024/06/08 03:09
地址:http://oj.leetcode.com/problems/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.
思路:permutation的规则,每次都是连续升序。归纳一下就是,只有之前有(n-1)!个permutations时,第1个数才增1.(排列数:n-1个数有(n-1)!的排列)。根据这个构造算法
c++ 参考代码:
class Solution {public: int factorial(int num) { int ans = 1; while(num>=2) ans *= num--; return ans; } string getPermutation(int n, int k) { string ans = ""; vector<int>vec(n, 0); for(int i = 0; i<n; ++i) vec[i] = i+1; int idx = 0, fa = 0; while(!vec.empty()) { fa = factorial(n-1); if(k) idx = (k-1) / fa; else idx = n-1; ans += vec[idx] + '0'; vec.erase(vec.begin()+idx); k = k % fa; --n; } return ans; }};
python参考代码:
class Solution: # @return a string def getPermutation(self, n, k): arr = range(1, n+1) ans = "" while arr: cur = (k-1) // math.factorial(n-1) ans += str(arr[cur]) k %= math.factorial(n-1) n -= 1 arr.pop(cur) return ans
话说python取list中的-1属性太好用了,代码这么简洁。c++里还没有直接算阶乘的。
但是python运行时间228ms, c++运行时间才8ms.
是不是OJ里引入了太多库了,实际上可能差不了这大。
0 0
- Leetcode_permutation-sequence(c++ and python version)
- LeetCode_Permutation Sequence
- leetCode_Permutation Sequence
- Leetcode_count-and-say(c++ and python version)
- Leetcode_linked-list-cycle(c++ and python version)
- Leetcode_climbing-statirs (c++ and python version)
- Leetcode_pascals-triangle (updated c++ and python version)
- Leetcode_unique-paths (updated c++ and python version)
- Leetcode_path-sum (updated c++ and python version)
- Leetcode_jump-game (updated c++ and python version)
- Leetcode_two-sum (c++ and python version)
- Leetcode_longest-palindromic-substring(c++ and python version)
- Leetcode_word-break(c++ and python version)
- Leetcode_wildcard-matching(c++ and python version)
- Leetcode_powx-n(c++ and python version)
- Leetcode_valid-number(updated c++ and python version)
- Leetcode_jump-game-ii(c++ and python version)
- Leetcode_multiply-strings (updated c++ and python version)
- combobox 中文首字母检索功能
- 浅谈ANR及如何分析解决ANR(2)
- 重温struts2之类型转换
- quick-cocos2d-x图片资源加密 (转)
- c13
- Leetcode_permutation-sequence(c++ and python version)
- 设计模式之适配器模式&外观模式
- 浅谈ANR及如何分析解决ANR(3)
- 对话框
- EXPORT_SYMBOL宏
- 又一HTML编辑器Simditor
- 数据结构——bitmap
- 黑马程序员笔记——Java基础
- 问:如何打包.ipa,然后用Application Loader提交到app store?