第八周算法分析与设计:Permutation Sequence
来源:互联网 发布:keep 知乎 编辑:程序博客网 时间:2024/06/05 01:10
算法描述:
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, forn = 3
):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
题目来自此处
解题思路:
这题目不用写出n以内数字的全排列(其实不会写),因为第几个全排列与它排第几有一定的数学联系。
可以把一整个全排列按其第一个、第二个….数字分成一组组,那么 1~n
的数组,在每次循环中从这个数组中得到索引的数字,得到后删去,每次索引中第几个数字跟数组中对应的数字是刚好对应的。
class Solution {public: string getPermutation(int n, int k) { string result = ""; vector<int>nums; nums.push_back(1); for(int i=1;i<=n;i++){ nums.push_back(i); } k--; while(n){ int index = (double)k/factorial(n-1)+1; result += (nums[index]+'0'); nums.erase(nums.begin()+index); k -= factorial(n-1)*(index-1); n--; } return result; } int factorial(int n){ if(n <= 1) return 1; else return n*factorial(n-1); }};
这个算法的时空复杂度都是
0 0
- 第八周算法分析与设计:Permutation Sequence
- 算法分析与设计第八周
- 算法分析与设计第十九周: 567. Permutation in String
- 算法分析与设计第八周:300. Longest Increasing Subsequence
- 算法分析与设计课程作业第八周#1
- Permutation Sequence算法详解
- 算法<Permutation Sequence>
- 算法设计与应用基础-第八周
- 算法设计与应用基础:第八周
- 【算法分析与设计】【第八周】712. Minimum ASCII Delete Sum for Two Strings
- 算法分析与设计丨第八周丨LeetCode(12)——Friend Circles(Medium)
- 算法设计与应用基础:第八周(1)
- 算法结构与设计基础作业第八周
- Leetcode算法学习日志-60 Permutation Sequence
- 算法分析与设计
- 算法设计与分析
- 算法分析与设计
- 算法设计与分析
- Vector3.Lerp
- 欢迎使用CSDN-markdown编辑器
- CSU 1869 中南大学网络赛C题 树上最大值
- HDU4586 Play the Dice (期望)
- springmvc中的注解
- 第八周算法分析与设计:Permutation Sequence
- 学习淘淘商城第二十四课(前台系统工程搭建)
- OpenCv3.2.0+python
- 警车
- POJ 2631 Roads in the North 树上最长路 树型DP
- git推送项目到github
- (map简单使用) Flying to the Mars
- poj 3279 Fliptile(开关问题)
- HDU2586【LCA在线算法】