Permutation Sequence
来源:互联网 发布:c语言移位操作 编辑:程序博客网 时间:2024/06/11 04:26
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.
首先采用DFS方法来做,但是太慢,k=9时就超时。
然后仔细分析规律,可以发现:
设变量K1 = K
a1 = K1 / (n-1)!// 最左位
同理,a2的值可以推导为
K2 = K1 % (n-1)!
a2 = K2 / (n-2)!
...
K(n-1) = K(n-2) /2!
a(n-1) = K(n-1) / 1!
an = K(n-1)
具体实现的过程中,需要一个数组来保存剩余可以用的数字(因为不能重复),用作当前位后需要删除该数字。
每次循环找到没使用过的数中第k/data[i]个数就是当前位的数字,data[i]保存(n-1)!的值。
注意:因为下标从0开始,需要k--
string getPermutation(int n, int k){ int data[n+1]; data[0]=1; int num[n]; for(int i=1; i<=n; i++) { data[i]=data[i-1]*i; num[i-1]=i; } string result; k--; for(int i=n-1; i>=0; i--) { int div=k/data[i]; result += (char)(num[div] + '0'); for(int j = div; j < n; j++) num[j] = num[j+1]; k=k%data[i]; } return result;}
=================== DFS 超时方法 ================================
vector<bool> used;string res;int temp[10];void Permute(int &n, int depth, int &k){ if(depth==n) { k--; if(k==0) { for(int i=0; i<n; i++) res += (char)(temp[i] + '0'); } } else for(int i=1; i<=n; i++) { if(used[i]==false) { used[i]=true; temp[depth]=i; Permute(n,depth+1,k); used[i]=false; } }}string getPermutation(int n, int k){ for(int i=0; i<=n; i++) used.push_back(false); Permute(n,0,k); return res;}
0 0
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- 使用EditText+ListView并结合TextWatcher实现输入关键字筛选数据
- 在Windows的Tomcat环境下部署Solr 4.7.0
- Arch Linux 下Intel + NVIDIA 双显卡3D 游戏配置(dota2@steam)
- 把网络图片转换为bitmap并显示在ImageView中
- Android触摸事件onScroll和onFling特别重要啊,要区分
- Permutation Sequence
- Linux下使用Samba服务器举例
- Mahout之bayes算法学习(一)
- 向浏览器输出excel文件的简单办法,不依赖第三方类库
- 童年汇---在游戏中教与学
- [NWPU][2014][TRN][3]搜索 总结
- [leetcode] Populating Next Right Pointers in Each Node
- Struts2+Hibernate4+Spring4整合
- logback的日期和文件大小共同作用日志分割