题目

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):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "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;
}
};

最新文章

  1. Oracle分析函数(一)
  2. 11、Linq的使用
  3. 自定义UITableViewCell
  4. 读取Excel列内容
  5. 18款 非常实用 jquery幻灯片图片切换
  6. 一个现代化的JSON库Moshi针对Android和Java
  7. Hibernate3 第一天
  8. Java实现Android,iOS设备实时监控
  9. 长整形 Unix系统毫秒时间 (long类型) 转换为时间格式
  10. mysql安装问题(一)
  11. Djangon
  12. springboot 集成 jpa/hibernate
  13. Bootstrap关闭当前页
  14. Ubuntu + python pip遇到的问题
  15. mysql ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
  16. Flink 中的kafka何时commit?
  17. 何为仿射变换(Affine Transformation)
  18. 高中生的IT之路-1.5西餐厅服务生
  19. mongo学习- mapReduce操作事例
  20. Logback Pattern 日志格式配置

热门文章

  1. Keymob带你玩转新广告法下的移动营销
  2. shell中的数值计算1/3=0.33
  3. MySQL-5.6.30 (OpenLogic CentOS7.2)
  4. co-dialog弹出框组件-版本v2.0.0
  5. select into outfile
  6. Java源码——HashMap的源码分析及原理学习记录
  7. MySQL的入门与使用,sqlyog对数据库,表和数据的管理
  8. ubuntu web server ipython notebook install
  9. 转:Python集合(set)类型的操作
  10. UNC路径格式