### 问题描述

https://leetcode.com/problems/permutation-sequence/#/description

he 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.

Note: Given n will be between 1 and 9 inclusive.

### 算法

1. 1 + {2,3}的全排列
2. 2 + {1,3}的全排列
3. 3 + {1,2}的全排列

### 代码

#### 循环版本

public String getPermutation(int n, int k) {
char[] nums = new char[]{'1','2','3','4','5','6','7','8','9'};
String tmp = "";
for(int i=0;i<n;i++) {
tmp += nums[i];
}
StringBuffer s = new StringBuffer(tmp);
String r = "";
while(k>0&&!s.toString().equals("")) {
// 计算 (n-1)的排列个数cnt
int cnt = 1, i = s.length()-1;
while(i > 1) {
cnt*=i;
i-=1;
}
int pos = (k-1)/cnt;
r += s.charAt(pos);
s = s.deleteCharAt(pos);
k -= pos * cnt;
}
return r;
}


#### 递归版本

 public String getPermutation1(int n, int k) {
char[] nums = new char[]{'1','2','3','4','5','6','7','8','9'};
String s = "";
for(int i=0;i<n;i++) {
s += nums[i];
}
return fun(new StringBuffer(s), k);
}

public String fun(StringBuffer s, int k) {
if(k<0 || s.toString().equals("")) return "";
int cnt = 1, tmp = s.length()-1;
while(tmp > 1) {
cnt*=tmp;
tmp-=1;
}
int pos = (k-1)/cnt;
return s.charAt(pos) + fun(s.deleteCharAt(pos), k - pos*cnt);
}


LeetCode解题代码仓库：https://github.com/zgljl2012/leetcode-java