博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Permutation Sequence
阅读量:7238 次
发布时间:2019-06-29

本文共 1195 字,大约阅读时间需要 3 分钟。

题目:

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.

思路:

除法和求余运算,对每一组数往下递推

package permutation;import java.util.ArrayList;import java.util.List;public class PermutationSequence {    public String getPermutation(int n, int k) {        List
l = new ArrayList
(); for (int i = 1; i <= n; ++i) l.add(i); --k; StringBuilder sb = new StringBuilder(); for (int i = n; i > 0; --i) { int fib = fib(i - 1); int index = k / fib; k = k % fib; sb.append((char)('0' + l.get(index))); l.remove(index); } return sb.toString(); } private int fib(int n) { int res = 1; for (int i = 1; i <= n; ++i) res *= i; return res; } public static void main(String[] args) { // TODO Auto-generated method stub PermutationSequence p = new PermutationSequence(); System.out.println(p.getPermutation(4, 5)); }}

 

转载地址:http://earfm.baihongyu.com/

你可能感兴趣的文章
中国现状,顺口溜
查看>>
ylb:使用sql语句实现添加、删除约束
查看>>
【RoR win32】提高rails new时bundle install运行速度
查看>>
固定滚动菜单
查看>>
CI 结合Bootstrap 分页
查看>>
windows 2008 怎么对外开放端口
查看>>
[cocos2d-x 3.0] 触摸显示器
查看>>
Linux 修改计算机名
查看>>
python --subprocess 范例
查看>>
菜鸟学SSH(十二)——Hibernate与Spring配合生成表结构
查看>>
Python IO多路复用
查看>>
op挂载摄像头
查看>>
json和pickle
查看>>
Mac系统的下载(图文详解)
查看>>
【UESTC 482】Charitable Exchange(优先队列+bfs)
查看>>
通过VS2010的内存分析工具来分析程序性能问题
查看>>
mini-cygwin
查看>>
如何能低成本地快速获取大量目标用户,而不是与竞争对手持久战?
查看>>
三分钟教你同步 Visual Studio Code 设置
查看>>
程序员,你是选择25k的996还是18k的8小时工作日?
查看>>