Instance of subset sum problem
I have a problem which is a pretty clear instance of the subset sum开发者_StackOverflow problem:
"given a list of Integers in the range [-65000,65000], the function returns true if any subset of the list summed is equal to zero. False otherwise."
What I wanted to ask is more of an explanation than a solution.
This was an instance-specific solution I came up before thinking about the complexity of the problem.
- Sort the array A[] and, during sort, sum each element to a counter 'extSum' (O(NLogN))
- Define to pointers low = A[0] and high = A[n-1]
- Here is the deciding code:
while(A[low]<0){ sum = extSum; if(extSum>0){ while(sum - A[high] < sum){ tmp = sum - A[high]; if(tmp==0) return true; else if(tmp > 0){ sum = tmp; high--; } else{ high--; } } extSum -= A[low]; low++; high = n - 1; } else{ /* Symmetric code: switch low, high and the operation > and < */ } } return false;
First of all, is this solution correct? I made some tests, but I am not sure...it looks too easy...
Isn't the time complexity of this code O(n^2)?I already read the various DP solutions and the thing I would like to understand is, for the specific instance of the problem I am facing, how much better than this naive and intuitive solution they are. I know my approach can be improved a lot but nothing that would make a big difference when it comes to the time complexity....
Thank you for the clarifications
EDIT: One obvious optimization would be that, while sorting, if a 0 is found, the function returns true immediately....but it's only for the specific case in which there are 0s in the array.
Hmm, I think {0} will beat your answer.
Because it will simply ignore while and return false.
精彩评论