这里有一个稍微不同的看法。我们可以认为元素m在子序列中可以是kth的方式数是任何元素(包括m)之前出现的所有方式的总和可以是(k-1)th。然而,当我们向右移动时,唯一需要更新的是m;其他总和保持不变。
例如,
// We want to avoid counting [1,1,1], [1,2,1], etc. twice
[1, 2, 1, 1, 1]
(为方便起见垂直显示数组)
<- k ->
[1, -> 1: [1, 0, 0]
2, -> 2: [1, 1, 0]
1, -> 1: [1, 2, 1]
1, -> 1: [1, 2, 3]
1] -> 1: [1, 2, 3]
现在如果我们添加另一个元素,比如 3,
...
3] -> 3: [1, 2, 3]
// 1 means there is one way
// the element, 3, can be first
// 2 means there are 2 ways
// 3 can be second: sum distinct
// column k[0] = 1 + 1 = 2
// 3 means there are 3 ways
// 3 can be third: sum distinct
// column k[1] = 2 + 1 = 3
汇总不同的k[2] 列:
0 + 3 + 3 = 6 subsequences
[1,2,1], [2,1,1], [1,1,1]
[1,1,3], [2,1,3], [3,2,1]
每列的 sum-distinct 可以在每次迭代时在 O(1) 中更新。当前元素的 k 总和(我们为每个元素更新一个列表),取 O(k),在我们的例子中是 O(1)。
JavaScript 代码:
function f(A, k){
A.unshift(null);
let sumDistinct = new Array(k + 1).fill(0);
let hash = {};
sumDistinct[0] = 1;
for (let i=1; i<A.length; i++){
let newElement;
if (!hash[A[i]]){
hash[A[i]] = new Array(k + 1).fill(0);
newElement = true;
}
let prev = hash[A[i]].slice();
// The number of ways an element, m, can be k'th
// in the subsequence is the sum of all the ways
// the previous occurence of any element
// (including m) can be (k-1)'th
for (let j=1; j<=k && j<=i; j++)
hash[A[i]][j] = sumDistinct[j - 1];
for (let j=2; j<=k && j<=i; j++)
sumDistinct[j] = sumDistinct[j] - prev[j] + hash[A[i]][j];
if (newElement)
sumDistinct[1] += 1;
console.log(JSON.stringify([A[i], hash[A[i]], sumDistinct]))
}
return sumDistinct[k];
}
var arr = [1, 2, 1, 1, 1, 3, 2, 1];
console.log(f(arr, 3));