查找系列的第X个术语

时间:2016-02-08 05:18:34

标签: c++ arrays algorithm

我有一个简单的问题。

我有一个N个数组A []。我必须执行这个操作:

  WrdArray() = Split(Stringtable, " = ")
                For i = LBound(WrdArray) To UBound(WrdArray)
                   strg = strg & vbNewLine & WrdArray(i)
                Next i
           MsgBox strg  

到数组A [] k次。执行此操作k次后,我必须输出第X个索引元素。

用蛮力做,将导致TLE。

我正在寻找一些模式,但是,我找到了一个并不完美的解决方案。

你能帮助我,找到一个更有效的解决方案来解决这个问题。

我有一个例子,清除问题。

我们假设数组for(i = 2; i<=N; i++) A[i] = A[i] + A[i-1] A,我需要执行上述操作3次:

第一回合后的数组:[1,2,3]
第二回合后的阵列:A=[1,3,6]
第三回合后的数组:A=[1,4,10]

所以,如果我现在需要找到数组的第二个元素,那么它将是5。

1 个答案:

答案 0 :(得分:1)

我看看Pascal的三角形(如@MBo所说)你可能会注意到在k次之后,在最终结果中每个数字加入的次数等于对角线后面的三角形中的一个正方形。让我们看一个例子:

enter image description here

此图像对应前三个元素的四次迭代。所以,正如你可以看到我们的输入k等于要返回的元素的索引的次数和n,我们所要做的就是将每个数字相乘对角线填充蓝色直到红线(图像配置对应k = 4n = 2)。

之后,我们有了这个公式:

enter image description here

现在,为了改进我们计算上面公式的方法,我们可以使用动态编程并从0 ... k + n计算阶乘函数(注意序列中较大的数字是k-1 + n) 。有了这个,我们可以在一个恒定的时间内访问factorial(n)。另外,如果我们在求和中扩展组合因子,我们会注意到因子(k - 1 + i - i)! = (k - 1)!所以,我们可以把它放在求和之外。

以下是代码:

#include "stdafx.h"
#include "iostream"

using namespace std;

int findingXth(int a[], int n, int k, int factorial[]){

    if (k == 0)
        return a[n];

    int result = 0;

    for (int i = 0; i <= n; ++i)
    {
        int up = k - 1 + i;
        result += (factorial[up] / factorial[i]) * a[n - i];
    }
    return result / factorial[k - 1];
}

int main(int argc, _TCHAR* argv[])
{
    int a[3] = { 1, 2, 3 };
    int n = 2;
    int k = 3;

    int factorial[100000]; // probably the expecification of the problem has some upper bounds for n and k (the length of the factorial array can be set to n+k+1);
    factorial[0] = 1;

    for (int i = 1; i < n + k; i++)
    {
        factorial[i] = factorial[i - 1] * i;
    }

    int result = findingXth(a, n, k, factorial);

    std::cout << result;

    return 0;
}