简体   繁体   English

查找所有总和等于零的不间断子序列

[英]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.

相关问题 总和可被 k 整除的子序列的数量 - number of subsequences whose sum is divisible by k 查找列表中的所有子序列 - Find all subsequences in list 给定一个数组,找到总和等于给定总和的元素对,并返回其索引的总和 - Given an array find element pairs whose sum is equal to the given sum and return the sum of their indices 如何找到等于给定总和的所有组合? - How to find all combinations that equal a given sum? 如何找到两个总和等于Python中目标总和的索引? - How can I find the indices of any two of the numbers, whose sum is equal to the target sum in Python? 给定大小为3 x 3的矩阵垫,请找到其最终累积总和大于或等于tO 150的每一行中的所有偶数 - Given a matrix mat of size 3 x 3. Find all the even numbers situated in each of the row(s) whose end cumulative sum is greater than or equal tO 150 如何编写一个通用的 function 来找到那些总和为零的数组元素? - How to write a general function to find those elements of array whose sum is zero? 从4个给定的数组(未排序)中,找到每个数组的元素,其总和等于某个数字X. - From 4 given arrays(not sorted), find the elements from each array whose sum is equal to some number X 给定一个由 N 个整数组成的数组和一个整数 K,找出该数组中总和等于 K 的元素对的数量 - Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K 数组中连续子序列的总和 - Sum of contigous subsequences in an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM