0,1,...,(N - 1)
。我的目标是找到给定排列的字典序索引,仅使用O(1)
空间。
此问题以前已被提出,但我找到的所有算法都使用了 O(N)
空间。我开始认为这是不可能的。但如果能减少分配数量,这将对我非常有帮助。
0,1,...,(N - 1)
。我的目标是找到给定排列的字典序索引,仅使用O(1)
空间。
此问题以前已被提出,但我找到的所有算法都使用了 O(N)
空间。我开始认为这是不可能的。但如果能减少分配数量,这将对我非常有帮助。
考虑以下数据:
chars = [a, b, c, d]
perm = [c, d, a, b]
ids = get_indexes(perm, chars) = [2, 3, 0, 1]
重复排列的可能解决方案如下:
len = length(perm) (len = 4)
num_chars = length(chars) (len = 4)
base = num_chars ^ len (base = 4 ^ 4 = 256)
base = base / len (base = 256 / 4 = 64)
id = base * ids[0] (id = 64 * 2 = 128)
base = base / len (base = 64 / 4 = 16)
id = id + (base * ids[1]) (id = 128 + (16 * 3) = 176)
base = base / len (base = 16 / 4 = 4)
id = id + (base * ids[2]) (id = 176 + (4 * 0) = 176)
base = base / len (base = 4 / 4 = 1)
id = id + (base * ids[3]) (id = 176 + (1 * 1) = 177)
反向过程:
id = 177
(id / (4 ^ 3)) % 4 = (177 / 64) % 4 = 2 % 4 = 2 -> chars[2] -> c
(id / (4 ^ 2)) % 4 = (177 / 16) % 4 = 11 % 4 = 3 -> chars[3] -> d
(id / (4 ^ 1)) % 4 = (177 / 4) % 4 = 44 % 4 = 0 -> chars[0] -> a
(id / (4 ^ 0)) % 4 = (177 / 1) % 4 = 177 % 4 = 1 -> chars[1] -> b
可能的排列数由num_chars ^ num_perm_digits
给出,其中num_chars
是可能字符的数量,num_perm_digits
是排列中数字的数量。
这需要O(1)
的空间,将初始列表视为固定成本;它需要O(N)
时间,其中N
是您的排列将具有的数字数。
根据上述步骤,您可以执行以下操作:
function identify_permutation(perm, chars) {
for (i = 0; i < length(perm); i++) {
ids[i] = get_index(perm[i], chars);
}
len = length(perm);
num_chars = length(chars);
index = 0;
base = num_chars ^ len - 1;
base = base / len;
for (i = 0; i < length(perm); i++) {
index += base * ids[i];
base = base / len;
}
}
这是一个伪代码,但也很容易转换为任何语言(:
aaaa,aaab,aaac,...
这样的排列都被考虑在内。我会尝试为没有重复的排列制作一个变化。 - Rubens以漂亮的格式将任何N选K的所有K索引输出到文件中。 K索引可以替换为更具描述性的字符串或字母。
将K索引转换为排序二项式系数表中条目的正确词典序索引或排名。这种技术比依赖迭代的旧技术快得多。它通过使用Pascal三角形固有的数学属性来实现,与迭代整个集合相比非常高效。
将排序的二项式系数表中的索引转换为相应的K索引。我认为它也比旧的迭代解决方案更快。
使用Mark Dominus方法计算二项式系数,这样不太可能溢出,并且可以处理更大的数字。
该类是用.NET C#编写的,并提供了一种使用通用列表来管理与问题相关的对象的方法(如果有)。此类的构造函数接受一个名为InitTable的bool值,当为true时,将创建一个通用列表来保存要管理的对象。如果此值为false,则不会创建该表。不需要创建表格即可使用上述4种方法。提供了访问器方法来访问表格。
有一个相关的测试类,展示了如何使用该类及其方法。它已经通过了2个案例的广泛测试,没有已知的错误。
要阅读关于这个类的内容并下载代码,请参见将二项式系数制表化。
以下经过测试的代码将迭代每个唯一组合:
public void Test10Choose5()
{
String S;
int Loop;
int N = 10; // Total number of elements in the set.
int K = 5; // Total number of elements in each group.
// Create the bin coeff object required to get all
// the combos for this N choose K combination.
BinCoeff<int> BC = new BinCoeff<int>(N, K, false);
int NumCombos = BinCoeff<int>.GetBinCoeff(N, K);
// The Kindexes array specifies the indexes for a lexigraphic element.
int[] KIndexes = new int[K];
StringBuilder SB = new StringBuilder();
// Loop thru all the combinations for this N choose K case.
for (int Combo = 0; Combo < NumCombos; Combo++)
{
// Get the k-indexes for this combination.
BC.GetKIndexes(Combo, KIndexes);
// Verify that the Kindexes returned can be used to retrive the
// rank or lexigraphic order of the KIndexes in the table.
int Val = BC.GetIndex(true, KIndexes);
if (Val != Combo)
{
S = "Val of " + Val.ToString() + " != Combo Value of " + Combo.ToString();
Console.WriteLine(S);
}
SB.Remove(0, SB.Length);
for (Loop = 0; Loop < K; Loop++)
{
SB.Append(KIndexes[Loop].ToString());
if (Loop < K - 1)
SB.Append(" ");
}
S = "KIndexes = " + SB.ToString();
Console.WriteLine(S);
}
}
在geekviewpoint上有一个解决这个问题的Java方案。它对为什么是正确的进行了很好的解释,代码易于理解。 http://www.geekviewpoint.com/java/numbers/permutation_index。它还有一个单元测试,可以使用不同的输入运行代码。
这个想法并没有什么新意,但是使用Numpy实现了一个完全矩阵化的方法,没有显式的循环或递归(易于调整):
import numpy as np
import math
vfact = np.vectorize(math.factorial, otypes='O')
def perm_index(p):
return np.dot( vfact(range(len(p)-1, -1, -1)),
p-np.sum(np.triu(p>np.vstack(p)), axis=0) )
如果您想假设算术运算是恒定时间,这里有一种方法:
def permutationIndex(numbers):
n=len(numbers)
result=0
j=0
while j<n:
# Determine factor, which is the number of possible permutations of
# the remaining digits.
i=1
factor=1
while i<n-j:
factor*=i
i+=1
i=0
# Determine index, which is how many previous digits there were at
# the current position.
index=numbers[j]
while i<j:
# Only the digits that weren't used so far are valid choices, so
# the index gets reduced if the number at the current position
# is greater than one of the previous digits.
if numbers[i]<numbers[j]:
index-=1
i+=1
# Update the result.
result+=index*factor
j+=1
return result
我特意写出了某些计算,这些计算可以使用一些Python内置操作更简单地完成,但我想让它更明显,即没有额外的非常量空间被使用。
正如maxim1000所指出的那样,表示结果所需的位数随着n的增加而快速增长,因此最终需要大整数,这些大整数不再具有恒定时间算术,但我认为这段代码解决了你问题的本质。
有N!个排列。为了表示索引,您至少需要N位。
ceil(log2(N!))
位。 - Todd Lehman