【问题标题】:General formula for a recurrence relation?递归关系的一般公式?
【发布时间】:2016-11-27 13:33:36
【问题描述】:

我正在解决一个编码问题,并找出了以下关系以找到可能的排列数:

one[1] = two[1] = three[1] = 1

one[i] = two[i-1] + three[i-1]

two[i] = one[i-1] + three[i-1]

three[i] = one[i-1] + two[i-1] + three[i-1]

我可以很容易地使用 for 循环 来找出各个数组的值直到 n,但 n 的值是 10^9 的顺序,我赢了'无法从1 迭代到如此庞大的数字。

对于n的每个值,我需要在O(1)时间输出(one[n] + two[n] + three[n]) % 10^9+7的值。

一些结果:

  • 对于 n = 1,结果 = 3
  • 对于 n = 2,结果 = 7
  • 对于 n = 3,结果 = 17
  • 对于 n = 4,结果 = 41

在花费数小时后,我无法找到上述n 的通用公式。谁能帮帮我。

编辑:

n = 1, result(1) = 3
n = 2, result(2) = 7
n = 3, result(3) = result(2)*2 + result(1) = 17
n = 4, result(4) = result(3)*2 + result(2) = 41

所以,result(n) = result(n-1)*2 + result(n-2)T(n) = 2T(n-1) + T(n-2)

【问题讨论】:

  • 你试过纸、铅笔和一些代数吗?
  • 是的.. 试着用铅笔在纸上找出一个图案。没找到。虽然不如代数...
  • 好吧,我可以告诉你,乍一看,它看起来并不难弄清楚。不幸的是,我没有时间参与其中。再试一次,这次更努力。
  • 顺便说一句,result[n] = one[n] + two[n] + three[n] 看起来不属于那里。
  • @FDavidov:已编辑。删除了result[n]

标签: algorithm formula recurrence


【解决方案1】:

您可以使用矩阵来表示递归关系。 (我已将onetwothree 重命名为abc)。

(a[n+1]) = ( 0 1 1 ) (a[n])
(b[n+1])   ( 1 0 1 ) (b[n])
(c[n+1])   ( 1 1 1 ) (c[n])

使用这种表示形式,可以通过矩阵求幂(以您的大数为模)来计算大 n 的值,并使用平方求幂。这将在 O(log n) 时间内为您提供结果。

(a[n]) = ( 0 1 1 )^(n-1) (1)
(b[n])   ( 1 0 1 )       (1)
(c[n])   ( 1 1 1 )       (1)

这里有一些 Python 从头开始​​实现这一切:

# compute a*b mod K where a and b are square matrices of the same size
def mmul(a, b, K):
    n = len(a)
    return [
        [sum(a[i][k] * b[k][j] for k in xrange(n)) % K for j in xrange(n)]
        for i in xrange(n)]

# compute a^n mod K where a is a square matrix
def mpow(a, n, K):
    if n == 0: return [[i == j for i in xrange(len(a))] for j in xrange(len(a))]
    if n % 2: return mmul(mpow(a, n-1, K), a, K)
    a2 = mpow(a, n//2, K)
    return mmul(a2, a2, K)

M = [[0, 1, 1], [1, 0, 1], [1, 1, 1]]

def f(n):
    K = 10**9+7
    return sum(sum(a) for a in mpow(M, n-1, K)) % K

print f(1), f(2), f(3), f(4)
print f(10 ** 9)

输出:

3 7 17 41
999999966

即使在 n=10**9 的情况下,它也能立即有效地运行。

【讨论】:

  • 这是一种用于快速计算递归关系的标准技巧(例如:斐波那契)。
猜你喜欢
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 2020-11-09
  • 2014-12-26
  • 1970-01-01
相关资源
最近更新 更多