如何解决这个组合计数问题?

时间:2018-10-26 17:51:54

标签: combinatorics counting

给定n个长3-digit (possible digits are 1, 2, 3)的字符串,需要使用以下操作来计算所有可能形成的不同数字的数量:

1) If the current digit is 1, then add 0 to the current number.
2) If the current digit is 2, then subtract k from the current number.
3) If the current digit is 3, then add p to the current number.

例如,如果n = 3, k = 2, and p = 5,ans = 10如下:

n = 3的所有可能序列为:

111
112
113
121
122
123
131
132
133
211
212
...
...
333

得分的示例计算为(say, for 132) = 0+5-2 = 3

目前,我正在解决以下组合问题:

1) Calculating and saving all possible k's as 0k, 1k, 2k, 3k, ..., nk (Saved in array AK)
2) Calculating and saving all possible p;s as 0p, 1p, 2p, 3p, ..., np (Saved in array AP)
3) Iterating for each ith element in AK, iterate from 0 to (n-i) in AP and save each summation of AK[i] + AP[j] in a set.
4) Finally, calculating the size of the set, which is the answer.

不幸的是,这种方法很O(n^2)

此问题是否存在线性时间解决方案?

为方便起见,还有更多示例:

n = 10000, p = 16, k = 3 => ans = 189848
n = 6, p = 5, k = 2 => ans = 28
n = 6, p = 5, k = 3 => ans = 28
n = 6, p = 5, k = 4 => ans = 28

0 个答案:

没有答案