leetCode_Permutation Sequence
2016-08-18 09:19
375 查看
题意:在集合[1,2,...,n]中找出第k个组合序列
思路:相当于把每个组合序列编号,从最高位开始,看看每一位能填几。
代码如下:
string getPermutation(int n, int k)
{
vector<int> f;
bool isUsed[10];
int i,j,t,m;
string ans;
f.push_back(1);
j=1;
for(i=1; i<=8; i++)
{
j=j*i;
f.push_back(j);
}
for(i=1; i<=n; i++) isUsed[i]=false;
for(i=1; i<=n; i++)
{
for(j=n-1; i>=0; j--)
{
if(k>j*f[(n-i)])//要注意是j*f[(n-i)]不是f[j]*(n-i)
{
k-=j*f[(n-i)];
j++;
break;
}
}
m=0;
for(t=1; t<=n; t++)
{
if(isUsed[t]==false) m++;
if(m==j)
{
isUsed[t]=true;
break;
}
}
switch(t)
{
case 1:
ans+="1";
break;
case 2:
ans+="2";
break;
case 3:
ans+="3";
break;
case 4:
ans+="4";
break;
case 5:
ans+="5";
break;
case 6:
ans+="6";
break;
case 7:
ans+="7";
break;
case 8:
ans+="8";
break;
case 9:
ans+="9";
break;
default:
break;
}
}
return ans;
}
思路:相当于把每个组合序列编号,从最高位开始,看看每一位能填几。
代码如下:
string getPermutation(int n, int k)
{
vector<int> f;
bool isUsed[10];
int i,j,t,m;
string ans;
f.push_back(1);
j=1;
for(i=1; i<=8; i++)
{
j=j*i;
f.push_back(j);
}
for(i=1; i<=n; i++) isUsed[i]=false;
for(i=1; i<=n; i++)
{
for(j=n-1; i>=0; j--)
{
if(k>j*f[(n-i)])//要注意是j*f[(n-i)]不是f[j]*(n-i)
{
k-=j*f[(n-i)];
j++;
break;
}
}
m=0;
for(t=1; t<=n; t++)
{
if(isUsed[t]==false) m++;
if(m==j)
{
isUsed[t]=true;
break;
}
}
switch(t)
{
case 1:
ans+="1";
break;
case 2:
ans+="2";
break;
case 3:
ans+="3";
break;
case 4:
ans+="4";
break;
case 5:
ans+="5";
break;
case 6:
ans+="6";
break;
case 7:
ans+="7";
break;
case 8:
ans+="8";
break;
case 9:
ans+="9";
break;
default:
break;
}
}
return ans;
}
相关文章推荐
- 长按手势获取UITableView的indexPath值,删除某行
- 在js中获取easyui datagrid的数据
- Android UI(ProgressBar)详解
- require.js+vue+vue-router+vue-resource开发微信上传图片组件
- POJ 1699 Best Sequence
- 133 - The Dole Queued
- Android“UI适配技能”
- LeetCode--No.225--Implement Stack using Queues
- sys_guid()
- uid
- /how-do-you-sort-a-dictionary-by-value
- HDU 4126 Genghis Khan the Conqueror(树形dp,MST,破坏原有最小生成树边后的最小生成树代价)
- HDU 1423 Greatest Common Increasing Subsequence(动态规划+最长公共上升子序列)
- Java学习日志(13-2-StringBuffer/StringBuilder与基本数值类型包装类)
- NSOperation与NSOperationQueue多线程的实现
- Unknown class _TtC20MainTabBarController20MainTabBarController in Interface Builder file.解决方法
- bigbluebutton的EC2安装方法
- UE4 行走/飞行切换,上升下降
- 探秘Java中String、StringBuilder以及StringBuffer
- setValuesForKeysWithDictionary 使用方法