【Permutation Sequence】cpp
2024-09-07 19:00:58
题目:
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.
代码:
class Solution {
public:
string getPermutation(int n, int k)
{
std::stringstream result;
// if the digit has been used
int flag[];
for(int i = ; i<; ++i) flag[i]=;
// calculate each digit
int factorical,quotient,remaind=k-;
for (int i = ; i<=n; ++i)
{
factorical = Solution::getFactorical(n-i);
quotient = remaind/factorical;
int tmp = ;
for(int j=; j<=; ++j){
tmp = tmp + flag[j];
if ( tmp==(quotient+) ){
quotient = j;
break;
}
}
result << quotient;
flag[quotient] = ;
remaind = remaind%factorical; // update remaind
}
return result.str();
}
static int getFactorical(int n){
int result = ;
for (int i = ; i <= n; ++i){
result = result * i;
}
return result;
}
};
Tips:
1. 主要思路是康托编码,具体什么是康托编码(http://blog.sina.com.cn/s/blog_4bf7b6580100l2zs.html)
2. 把计算阶乘的代码单独列出来
3. 对于c++如何将int转为字符不太懂,因此用了sstream的这个方法,后面遇到其他的方法再改进一下。
======================================================
第二次过这道题,对康托编码的算法有些生疏了,参考了blog才回忆起来。然后扫了一些细节,形成了自己的代码。
class Solution {
public:
string getPermutation(int n, int k)
{
vector<char> ret;
vector<bool> visit(,false);
k = k-;
for ( int i=n-; i>=; --i)
{
int factor = Solution::factorial(i);
int num_less = k / factor;
// find num less
int j=;
int count = ;
for ( ; j<; ++j )
{
if ( !visit[j] )
{
if ( count==num_less ) break;
count++;
}
}
visit[j] = true;
ret.push_back(j+'');
k = k % factor;
}
return string(ret.begin(),ret.end());
}
static int factorial(int n)
{
if ( n== || n== ) return ;
int ret = ;
for ( int i = ; i<=n; ++i) ret = ret * i;
return ret;
}
};
最新文章
- Oracle分析函数(一)
- 11、Linq的使用
- 自定义UITableViewCell
- 读取Excel列内容
- 18款 非常实用 jquery幻灯片图片切换
- 一个现代化的JSON库Moshi针对Android和Java
- Hibernate3 第一天
- Java实现Android,iOS设备实时监控
- 长整形 Unix系统毫秒时间 (long类型) 转换为时间格式
- mysql安装问题(一)
- Djangon
- springboot 集成 jpa/hibernate
- Bootstrap关闭当前页
- Ubuntu + python pip遇到的问题
- mysql ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
- Flink 中的kafka何时commit?
- 何为仿射变换(Affine Transformation)
- 高中生的IT之路-1.5西餐厅服务生
- mongo学习- mapReduce操作事例
- Logback Pattern 日志格式配置
热门文章
- Keymob带你玩转新广告法下的移动营销
- shell中的数值计算1/3=0.33
- MySQL-5.6.30 (OpenLogic CentOS7.2)
- co-dialog弹出框组件-版本v2.0.0
- select into outfile
- Java源码——HashMap的源码分析及原理学习记录
- MySQL的入门与使用,sqlyog对数据库,表和数据的管理
- ubuntu web server ipython notebook install
- 转:Python集合(set)类型的操作
- UNC路径格式