[英]Find all uninterrupted subsequences whose sum is equal to zero
Say that we have an array of N integers and want to find all subsequences of consecutive elements which have the sum of the equal to zero. 假设我们有一个由N个整数组成的数组,并且想要找到具有等于零的和的连续元素的所有子序列。
Example: 例:
N = 9
array = [1, -2, 4, 5, -7, -4, 8, 3, -7]
Should output: 应该输出:
1 4
4 7
5 8
1 8
as each of the above are the start and end index of the subsequences with sum equal to zero. 因为上面的每个都是和等于零的子序列的开始和结束索引。
I came to the conclusion that there are N * (N + 1) / 2
such possible subsequences which would conclude in O(N^2) complexity if using a naive algorithm that exhaustively searches over all the possible solutions. 我得出的结论是,如果使用一种穷举搜索所有可能解的朴素算法,那么就有N * (N + 1) / 2
这样的可能子序列会以O(N ^ 2)复杂度得出结论。
I would like to know if there is any way to achieve this in O(N) complexity or something less than O(N^2)? 我想知道是否有任何方法可以实现O(N)复杂度或小于O(N ^ 2)的目标?
I am aware of the Subset sum problem which is a NP-complete problem but mine seems to be a bit easier as it only requires subsequences of consecutive elements. 我知道子集和问题是一个NP完全问题,但是我的问题似乎要容易一些,因为它只需要连续元素的子序列。
Thank you in advance. 先感谢您。
It is worse than you think. 比你想的还要糟。
There are potentially Θ(n²) uninterrupted subsequences that add up to zero, as in the following example: 潜在的Θ(n²)不间断子序列加起来等于零,如以下示例所示:
0 0 0 0 0 0 0 0 0
(Here, every subsequence adds up to zero.) (这里, 每个子序列加起来为零。)
Therefore, any algorithm that prints out the start and end index of all the required subsequences will necessarily have o(n²) worst-case complexity. 因此,任何打印出所有所需子序列的开始和结束索引的算法都将必然具有o(n²)最坏情况的复杂性。 Printing out their elements will require Θ(n³) time. 打印出它们的元素将需要Θ(n³)时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.