You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an array S of n integers, find all subsets of the array with 4 values where the 4 values sum up to a target number.
105
106
106
107
**Note**: The solution set must not contain duplicate quadruplets.
107
108
108
109
### Solution
109
-
After 3Sum, we already have the idea to change to a problem to a familiar problem we solved before. So, the idea here is straightforward. We just need to downgrade 4Sum to 3Sum. Then we can solve 4Sum.
110
110
111
-
It's easy to think that we loop the array and get the first the element, then the rest array is 3Sum problem. Since the code is pretty simple, I will avoid duplicate introducation here.
111
+
Foursum is a very straightforward extension to the threeSum algorithm. In threeSum, you kept track of 3 indices:
112
+
113
+
```
114
+
m -> <- r
115
+
[-4, -1, -1, 0, 1, 2]
116
+
l
117
+
```
118
+
119
+
For fourSum, you'll keep track of 4:
120
+
121
+
```
122
+
mr -> <- r
123
+
[-4, -1, -1, 0, 1, 2]
124
+
l ml ->
125
+
```
126
+
127
+
Here's the code for it (notice it is very similar to 3Sum):
0 commit comments