这是一个依赖于两个想法的 Python 解决方案。首先,动态编程计算分区而不生成分区。其次,如果第一个值是,i
那么我们可以将其视为一个盒子i * k
,顶部有一个部分。n-i*k
k-1
partition_cache = {}
def distinct_partition_count (n, k):
if n < k:
return 0
elif n < 1:
return 0
elif k < 1:
return 0
elif k == 1:
return 1
elif (n, k) not in partition_cache:
answer = 0
for i in range(1, n/k + 1):
answer = answer + distinct_partition_count(n - i*k, k-1)
partition_cache[(n, k)] = answer
return partition_cache[(n, k)]
def rank_distinct_partition (values):
values2 = sorted(values)
n = sum(values)
k = len(values)
answer = 0
highwater = 0
for v in values:
rise = v - highwater
for i in range(1, rise):
answer = answer + distinct_partition_count(n - k*i, k-1)
highwater = v
## BUG HERE: was n = n - rise
n = n - rise * k
k = k - 1
return answer
def find_ranked_distinct_partition (n, k, rank):
if k == 1 and rank == 0:
return [n]
elif distinct_partition_count(n, k) <= rank:
return None
elif rank < 0:
return None
else:
i = 1
while distinct_partition_count(n - i*k, k-1) <= rank:
rank = rank - distinct_partition_count(n - i*k, k-1);
i = i + 1
answer = find_ranked_distinct_partition(n - i*k, k-1, rank)
return [i] + [j + i for j in answer]
print(rank_distinct_partition([2, 3])
print(find_ranked_distinct_partition(5, 2, 1))