使用动态规划解决k-子向量问题
给定一个由 n 个整数组成的向量 V 和一个整数 k,k <= n,您需要一个最大长度的子向量(向量 的连续元素的序列),最多包含 k 个不同元素。
我用来解决问题的技术是动态规划。 该算法的复杂度必须是O(n*k)。
主要问题是如何计算向量的不同元素。你会怎样解决呢?
递归方程怎么写?
感谢您!!!。
Given a vector V of n integers and an integer k, k <= n, you want a subvector (a sequence of consecutive elements of the vector ) of maximum length containing at most k distinct elements.
The technique that I use for the resolution of the problem is dynamic programming.
The complexity of this algorithm must be O(n*k).
The main problem is how to count distinct elements of the vector. as you would resolve it ?
How to write the EQUATION OF RECURRENCE ?
Thanks you!!!.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道为什么你会坚持
O(n*k)
,这可以通过“滑动窗口”方法在O(n)
中解决。[left..right]
right
加 1(不违反“最多 k 个离散元素”要求),则执行否则left
增加 1检查是否可以在 #2 中增加
right
有点棘手。我们可以使用哈希表来存储窗口内每个元素出现的次数。因此,允许
right
增加的条件如下所示每次
left
或right
增加时,我们需要更新哈希(减少或增加给定元素的出现次数)。我很确定,这里的任何 DP 解决方案都会更长、更复杂。
I don't know why you would insist on
O(n*k)
, this can be solved inO(n)
with 'sliding window' approach.[left..right]
right
by 1 (without violating 'at most k disctint elements' requirement), do itleft
by 1Checking whether we can increase
right
in #2 is a little tricky. We can use hashtable storing for each element inside window how many times it occurred there.So, the condition to allow
right
increase would look likeAnd each time
left
orright
is increased, we'll need to update hash (decrease or increase number of occurrences of the given element).I'm pretty sure, any DP solution here would be longer and more complicated.
如果允许使用散列,您可以执行以下操作,
平均时间为 O(n)。
如果不是,这里有一个 O(n log n) 解决方案 - 这次是最坏的情况
我还可以告诉你一个在 O(n*b) 中对 V 进行排序的算法,其中 b 是整数的位数 - 如果这有帮助你。这是算法:
调用它
向量=V
开始索引 = 0
结束索引 = n-1
currentBit = 整数的位数 (=: b)-1。
这甚至根据要求使用动态编程。
您可以很容易地确定,这是 O(n*b) 时间,递归深度为 b。
If you allowed to use hashing, you could do the following
This is in average O(n) time.
If not here is an O(n log n) solution - this time worst case
I could also tell you an algorithm to sort V in O(n*b) where b is the bit count of the integers - if this helps you.Here is the algorithm:
Call it with
vector = V
begin_index = 0
end_index = n-1
currentBit = bit count of the integers (=: b)-1.
This even uses dynamic programming as requested.
As you can determine very easily this is O(n*b) time with a recursion depth of b.