leetCode 60.Permutation Sequence (排列序列) 解题思路和方法
2015-07-15 14:16
561 查看
The set
unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
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)!个序列。
具体代码如下:
[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 ; int[] data = new int ;//存阶乘的数据 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; } }
相关文章推荐
- 使用uiautomator获取应用内存
- 【原】设置iOS项目BuildVersion自动增加
- UIimageview tap 跳转
- iOS开发——UI基础-自定义构造方法,layoutSubviews,Xib文件,利用Xib自定义View
- 如何编译WinCE Bluetooth Stack并打开的默认LOG
- Forbidden (403) CSRF verification failed. Request aborted.
- UEFI HOB
- UEFI Drivers & UEFI Driver Model
- UEFI Images
- UEFI小结-Handle的来龙去脉
- UEFI Boot Flow
- EasyUI改变Layout的Region的宽高,位置等信息
- Android UI学习之---Button
- UI-程序的运行顺序
- SQL Server 阻止了对组件 \'Ad Hoc Distributed Queries\' 的访问
- [CareerCup] 1.1 Unique Characters of a String 字符串中不同的字符
- iOS开发——UI基础-懒加载,plist文件,字典转模型,自定义view
- Ubuntu——grub rescue 主引导修复
- 深入理解String、StringBuffrt、StringBuilder
- Android开发UI之控件-Android-PullToRefresh