Intuition
If we try to use brute-force algorithm to solve this problem, we will find O(2^n)
in complexity. But, since max of n
is 40, it’s too long to pass. Namely, $2^{40}\sim 10^{12}$. Also, although it looks like a dynamic programming problem, it’s not working either.
Surprisingly, it’s easier than I thought. All we have to do is divide it into half. That way, the complexity will became $2^{n/2}+2^{n/2}$, which has a maximum of $2^{20}+2^{20}=2^{21}\sim 2*10^{6}$.
But, that only include time of 2 brute-force divide. We have to also conquer it. There’s the procedure,
- devide all numbers into nums1, nums2 equaly
- nums1 -> map1 (possible sum, combinations), also, nums2 -> map2.
- for each map1 value, find a value in map2 that satisfy
val1 + val2 = target
.
Therefore, we get the total complexity is $Time=2*2^{n}*lg(2^n)+2^{n}*lg(2^n)={3}*2^{n}*n$ , where n has a maximum of 20. Namely, we obtain the worse case run time is
$$O_w({3}*2^{n}*n)={3}*2^{20}*20\sim {6}*10^7$$
Sample Code:
1 |
|