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 k th permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
用book数组指示当前还有哪些数字没有被放到数组arr里面,在修改并输出最后结果之后还要将它改回原来数组的样子。
public class Solution {
static int k;
static String s="";
public String getPermutation(int n, int m) {
k=m;
dfs(n);
return s;
}
public static void dfs(int n){
int[] arr = new int[n];
int[] book = new int[n];
dfs(0,arr,book);
}
private static void dfs(int step, int[] arr, int[] book){
if(step==arr.length){
if(k==1){
s="";
for(int i=0; i<arr.length; i++){
s=s+arr[i];
}
}
k--;
return;
}
for(int i=0; i<arr.length; i++){
if(book[i]==0){
arr[step]=i+1;
book[i] = 1;
dfs(step+1,arr,book);
book[i] = 0;
}
}
}
}