60. Permutation Sequence
来源:互联网 发布:网络大电影2017排行榜 编辑:程序博客网 时间:2024/06/06 03:53
60. Permutation Sequence
- Total Accepted: 65886
- Total Submissions: 249649
- Difficulty: Medium
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.
刚开始用全排列的常规方法,DFS进行顺序查找,超时
public class Solution { static int index = 0; public String getPermutation(int n, int k) { int[] visited = new int[n]; index = 0; return permutate(visited, n, k, ""); } String permutate(int[] visited, int n, int k, String nowStr){ String result = ""; if(nowStr.length() == n){ index++; return nowStr; }else{ for(int i = 1; i <= n; i++){ if(visited[i-1] == 0){ visited[i-1] = 1; nowStr += i; result = permutate(visited, n, k, nowStr); //System.out.println(index); if(index == k){ return result; } nowStr = nowStr.substring(0, nowStr.length()-1); visited[i-1] = 0; } } } return result; } }转换思路,An, An-1, ..... , A2, A1 An能表示的数字有n!,利用此规律,第一次确定最高位,第二次确定次高位。。。。。。。循环即可得到结果
public class Solution { static int num = 0; public String getPermutation(int n, int k) { String result = ""; int[] nums = new int[n+1]; int[] visited = new int[n+1]; nums[1] = 1; for(int i = 2; i <= n; i ++){ nums[i] = i * nums[i-1]; } for(int i = n; i >= 2; i --){ int times = k / nums[i-1]; if( k % nums[i-1] != 0){ times++; k = k % nums[i-1]; }else{ k = nums[i-1]; } int item = 1; for(int j = 1; j <= n; j++){ if(visited[j] == 0){ if(times >= 0){ times--; } if(times == 0){ result += j; visited[j] = 1; break; } } } } for(int j = 1; j <= n; j++){ if(visited[j] == 0){ result += j; visited[j] = 1; } } return result; } }
0 0
- LeetCode --- 60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60.Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- **LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- 60. Permutation Sequence
- [LeetCode]60. Permutation Sequence
- LeetCode *** 60. Permutation Sequence
- 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- hiho 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- HDU 5514 Game of Flying Circus
- SSDsim源码分析之 load_parameters
- 百度运用 FPGA 方法大规模加速 SQL 查询
- Linux进程通信
- 根据先序遍历和中序遍历得出二叉树。最终以后序遍历的形式输出。
- 60. Permutation Sequence
- QT Creator编译出现"常量中有换行符"解决.
- 为 Github 创造 Integration
- 树状数组
- Tyvj P1933 「Poetize3」绿豆蛙的归宿
- CSS中冻结布局
- Hive 2 安装
- 阿里巴巴的开源产品
- 使用ant编译,没有结果