个人思路总结:
C++递归解答,根据k和n的值确定string res中每一位的取值。 我们知道排列的每一位上都有n种选择,而每一种选择都有(n-1)!种排列方式。因此我们要从左往右依次确认每一位上应该取什么值。判断的方式就是每一位各种选择的排列总数之和是否大于k,一旦大于k,就可以确定此时的那个数字可以作为当前位的数字了。然后删除这个数字,进行下一次递归。
代码如下:
class Solution {
public:
string
getPermutation(int n
, int k
) {
string res
;
vector
<int> tmp
;
for(int i
=1;i
<=n
;i
++)
tmp
.push_back(i
);
dfs(res
,tmp
,n
,k
);
return res
;
}
void dfs(string
& res
, vector
<int>& tmp
, int n
, int k
)
{
if(tmp
.empty())
return;
int step
= multiy(n
-1);
int count
= 0, s
= step
;
while(k
>s
)
{
s
+= step
;
count
++;
}
res
+= to_string(tmp
[count
]);
tmp
.erase(tmp
.begin()+count
);
dfs(res
,tmp
,n
-1,k
-count
*step
);
}
int multiy(int n
)
{
if(n
<=1)
return 1;
else
return n
*multiy(n
-1);
}
};
转载请注明原文地址: https://yun.8miu.com/read-29018.html