leetCode 60.Permutation Sequence (排列序列) 解题思路和方法
2024-09-01 21:45:24
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.
思路:这一题还是比較难,暴力全然是找死的,超时没二话。可是数学归纳的方法不是每一个人都能想到,看了非常多资料,也才刚理解了一些思想。
规律:已知n的值,学过排列组合知道共同拥有n!种排列。
第一位每一个数字开头的序列都有(n-1)!
个序列,因此n个数字所以共同拥有n!个序列。
以此类推。第二位每个数开头都有(n-2)!
个序列。
详细代码例如以下:
public class Solution {
String str = "";
public String getPermutation(int n, int k) {
int[] num = new int[n];
int[] data = new int[n];//存阶乘的数据
int i = 0;
for(; i < n ;i++){
num[i] = i+1;
if(i == 0)
data[i] = 1;
else{
data[i] = data[i-1]*i;
}
}
k--;
while(--i > -1){//循环得到各位数字
int k1 = k/data[i];
int p = k1+(n-1-i);//数字的位置
swap(n-1-i,p,num);
if((k = k %data[i]) == 0)//k==0结束
break;
}
for(int x:num)//得到str
str += x;
return str;
}
//将数据插入,后面的依次后移
public void swap(int i,int j,int[] num)
{
int m = num[j];
for(int k=j;k>i;k--)
num[k]=num[k-1];
num[i]=m;
}
}
最新文章
- EasyUI+MVC+EF简单用户管理Demo(问题及解决)
- UI第十四节——UIAlertController
- Android RelativeLayout用到的一些重要的属性
- “vmware tools 只能虚拟机中安装”的解决方法
- Java数组的复制Arrays.copyOf()、System.arraycopy()、nums.clone()
- Web 通信 之 长连接、长轮询(转)
- 资料下载:生活方向盘PPT以及活动录音(2011.02)
- shell脚本的调试技巧
- ERP员工入职登记(五)
- Android ListView无法触发ItemClick事件
- ehcache 的配置
- scala学习笔记:高阶函数
- POJ 1050 To the Max -- 动态规划
- C++是怎么实现多态性的
- Windows下连接php5.3+sql server2008
- HDU 3486 Interviewe
- 学习TensorFlow,多层卷积神经网络
- 记录心得-FastJson分层解析demo示例
- 一个tomcat下部署不同端口多个应用
- 工作笔记—新浪微博Oauth2.0授权 获取Access Token (java)