[0-9]元素序列中增加的子序列数

时间:2014-06-27 17:03:32

标签: algorithm

在一系列未知范围值元素的情况下,问题Number of all increasing subsequences in given sequence给出了O(n ^ 2)的解。

在仅由区间[0,9]中的元素组成的序列的情况下,我已经听说过O(9 * n)中的解。如果你知道这个算法,请告诉我。

2 个答案:

答案 0 :(得分:1)

这是一个算法:

1)让我们调用dp[i] =具有最后一个元素i0 <= i <= 9)的递增子序列的数量。最初它用零填充。

2)现在我们可以迭代序列并按以下方式计算dp
我们假设当前元素是d0 <= d <= 9)。然后dp可以像这样更新:

for prev = 0...d - 1
    dp[d] += dp[prev] //continue one of the previous sequences.
dp[d] += 1 //start a new sequence that consists of only one element.

3)迭代序列的所有元素后,答案只是dp[i] 0 <= i <= 9的总和。

请注意,只有在假设算术运算具有O(1)时间复杂度的情况下,此算法才具有所需的复杂性(可能不是这种情况,因为增加的子序列的数量可能非常大)。

答案 1 :(得分:1)

改变与问题相关的算法,我相信这也应该满足复杂性要求:

input[i] = input array
n = size of input
dp[i] = number of increasing subsequences with i as the last element (same size as input)

initialize dp[i] = 0 for all 0 <= i < n

//Every possible input can be appended on to one previously found
//  increasing subsequence
for (j = 0; j <= 9; j++) {

  //Running total of increasing subsequences that occur earlier in the input using
  //  smaller numbers than j
  int smallerSum = 0;

  for (i = 0; i < n; i++) {

    //This spot in dp was tallied already, need to add it to the running total
    if (input[i] < j) {
      smallerSum += dp[i]

    //Add 1 to the running total, this should be the final answer for this spot in dp
    } else if (input[i] == j) {
      dp[i] = smallerSum + 1;
    }
  }
}

return the sum of all elements of dp

通常,嵌套的for循环是O(n ^ 2)的死亡赠品,但在这种情况下,我们循环一个常量,使其成为O(n)。

在一般情况下,该算法为O(n * k),其中n是输入数组的大小,k是可能的输入值的数量。