LeetCode刷题笔录Permutation Sequence
来源:互联网 发布:手机扫码软件 编辑:程序博客网 时间:2024/04/28 01:34
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,按顺序得到所有的permutation,直到得到第K个为止。
public class Solution {public String getPermutation(int n, int k) {boolean[] used = new boolean[n];List<String> res = new ArrayList<String>();helper(0, new int[] { 1 }, k, n, used, new StringBuffer(), res);return res.get(0);}public void helper(int level, int[] count, int k, int n, boolean[] used,StringBuffer str, List<String> res) {if (level == n) {if (count[0] < k) {count[0]++;return;} else {res.add(str.toString());return;}}if (count[0] <= k) {for (int i = 1; i <= n; i++) {if (used[i - 1] == true)continue;used[i - 1] = true;str.append(i);helper(level + 1, count, k, n, used, str, res);used[i - 1] = false;str.deleteCharAt(str.length() - 1);}}}}
在自己机器上没什么问题,不过在LeetCode的OJ里总会超时。这样的时间复杂度确实有点太高了。
0 0
- LeetCode刷题笔录Permutation Sequence
- LeetCode刷题笔录Next Permutation
- LeetCode刷题笔录Longest Consecutive Sequence
- [leetcode 刷题系列]Permutation Sequence
- LeetCode第60题之Permutation Sequence
- LeetCode: Permutation Sequence
- LeetCode Permutation Sequence
- [Leetcode] Permutation Sequence
- [LeetCode] Permutation Sequence
- leetcode 74: Permutation Sequence
- leetcode Permutation Sequence
- [leetcode] Permutation Sequence
- [LeetCode]Permutation Sequence
- LeetCode:Permutation Sequence
- LeetCode-Permutation SequencePermutation Sequence
- [leetcode] Permutation Sequence
- LeetCode - Permutation Sequence
- LeetCode:Permutation Sequence
- 【矩阵算法】distance transform用以提取手掌中心区域
- 史上最容易理解Spring的IoC和DI
- IOS数据持久化层
- C#一元二次方程
- [ffmpeg 扩展第三方库编译系列] 关于libopenjpeg mingw32编译问题
- LeetCode刷题笔录Permutation Sequence
- R语言 -- Q&A
- Bean Query 第一个版本(1.0.0)已发布
- 【基础算法】排序-复杂排序之一(归并排序)
- HttpClient 发送Json请求,结果返回Json
- 解决virtuallBox安装Ubuntu后分辨率小的问题
- Linux kernel的中断子系统之(一):综述
- hdu - 4973 - A simple simulation problem.(线段树单点更新 + 区间更新)
- Linux kernel的中断子系统之(二):IRQ Domain介绍