Redian新闻
>
算法题:如何将排列映射到编码?
avatar
算法题:如何将排列映射到编码?# JobHunting - 待字闺中
q*x
1
比如123的排列有6个,按次序可以映射到0到5。那么函数f("321") = 5,f("132") = 1
,等等。
假设P是k个不同数字/字母的某个排列,求f(P)。
另外求f的逆函数。
应该是个经典题吧?
avatar
r*t
2
做 bubble sort count 交换次数?
avatar
c*m
3
把阶乘当base。
这个是经典,搜索时候用于储存状态空间。但是感觉面试问这个算难的了。
avatar
q*x
4
太慢。

【在 r****t 的大作中提到】
: 做 bubble sort count 交换次数?
avatar
q*x
5
有参考链接吗?

【在 c****m 的大作中提到】
: 把阶乘当base。
: 这个是经典,搜索时候用于储存状态空间。但是感觉面试问这个算难的了。

avatar
H*e
6
就是算阶乘那个
假设要求第index=8的string(0 based, not 1)
abcd (4个) ,以a开头的有(4-1)!=6个,同理b/c/d/也是6个
8/6 = 1(所选的字母的位置) 8%6 = 2 (下一个index) 所以第一个字母是 b
然后recursion, 剩下 acd, (3-1)!=2 index=2, index/2= 1. index%2=0
所以第二个字母为c
剩下ad, (2-1)!=1, index=0, index/1=0, index%2 =0;
所以第三个字母为a
第四个字母为d
总体为bcad
同理,逆函数类似的idea.

【在 q****x 的大作中提到】
: 有参考链接吗?
avatar
c*e
7
Suppose 排列 1, 2, ..., n is expressed as a[n].
long index(int a[], int n) {
long idx=0;
for(int i=0;iidx+=(a[i]-1)*factorial(n-1-i);
return idx;
}
avatar
c*e
8
index()的逆函数
void reverseIndex(long index, int a[], int n) {
long idx = index;
for(int i=0;iint j=idx/factorial(n-i-1);
a[i]=j;
idx = idx % factorial(n-i-1);
}
}
avatar
s*n
9
这个对吗?假设1,2,3,4,n=4

【在 c**********e 的大作中提到】
: Suppose 排列 1, 2, ..., n is expressed as a[n].
: long index(int a[], int n) {
: long idx=0;
: for(int i=0;i: idx+=(a[i]-1)*factorial(n-1-i);
: return idx;
: }

avatar
s*n
10
long index(int a[], int n) {
long idx=0;
long factorial = 1;
for(int i=n-2;i>=0;i--) {
int rank = 0;
for (int j=i+1; iif (a[j]factorial = factorial* (n-i-1);
idx+=rank*factorial;
}
return idx;
}
avatar
h*a
11
What if the numbers in the array are not unique?

【在 s******n 的大作中提到】
: long index(int a[], int n) {
: long idx=0;
: long factorial = 1;
: for(int i=n-2;i>=0;i--) {
: int rank = 0;
: for (int j=i+1; i: if (a[j]: factorial = factorial* (n-i-1);
: idx+=rank*factorial;
: }

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。