【Leetcode】Permutation Sequence
来源:互联网 发布:7z解压软件 linux 编辑:程序博客网 时间:2024/04/28 06:50
题目链接:https://leetcode.com/problems/permutation-sequence/
题目:
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.
思路:
从左往右计算,先计算最高位。 应该为k/(n-1)! ,下一位应该是(k%(n-1)!)/(n-2)!,以此类推。
算法:
public String getPermutation(int n, int k) { int nums[] = new int[n]; int pCount=1; for(int i=0;i<nums.length;i++){ nums[i] = i+1; pCount *= (i+1);//n! } k--;//下标从0开始 String res = ""; for(int i=0;i<n;i++){ pCount /=n-i;//(n-i-1)! int r = k/pCount; res+=nums[r];//第r小的元素 for(int j=r;j<n-1-i;j++){ //获取第r小的元素 所以将已经用过的元素覆盖 nums[j] = nums[j+1]; } k = k%pCount; } return res; }
1 0
- 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
- LeetCode 60: Permutation Sequence
- Leetcode: Permutation Sequence
- leetcode Permutation Sequence
- LeetCode | Permutation Sequence
- LeetCode Permutation Sequence
- javaWeb使用siteMesh和adminLTE美观CRM系统搭建
- linux 解决man命令输出到文档打开乱码问题
- 【Leetcode】3Sum
- Archlinux MySQL PHP phpmyadmin Apache PHP-Apache Install
- android studio如何修改包名
- 【Leetcode】Permutation Sequence
- Hadoop之——hadoop2.5.2eclipse插件编译
- 【Leetcode】 Clone Graph
- Surface, SurfaceView和SurfaceHolder
- VS C# ADO.NET代码连接Access数据库
- 安装配置Jpcap,使用jpcap抓包
- 学习笔记—在laravel4.2中配置mongodb
- android Studio将String.xml中的字段导出。
- iOS原生Http请求,get post 异步