题目
求n个排序数的第k项
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.
code
public class Solution
{
private int sumcnt; //sumcnt item
private List<int> rtn = new List<int>(); //return value
public string GetPermutation(int n, int k)
{
//get the leftest digit for kTh item
int cal = 1;
for (int i = 1; i < n; i++) //(n-1)!
cal *= i;
int mod = k % cal;
int beg = mod == 0 ? k / cal : k / cal + 1;
sumcnt = (beg - 1) * cal;
//dfs
dfs(n, k, new List<int>(){beg}, 1);
//analysis result
String strs = string.Empty;
foreach (var i in rtn)
strs += i.ToString();
return strs;
}
private void dfs(int n, int k, List<int> s, int index)
{
if (s.Count == n)
{
if (++sumcnt == k)
rtn.AddRange(s);
return;
}
for (int i = 1; i <= n; i++)
{
if (s.Contains(i)) continue;
s.Add(i);
dfs(n, k, s, i);
s.RemoveAt(s.Count - 1);
}
}
}