# 四数之和

<p>给定一个包含 <em>n</em> 个整数的数组 <code>nums</code> 和一个目标值 <code>target</code>，判断 <code>nums</code> 中是否存在四个元素 <em>a，</em><em>b，c</em> 和 <em>d</em> ，使得 <em>a</em> + <em>b</em> + <em>c</em> + <em>d</em> 的值与 <code>target</code> 相等？找出所有满足条件且不重复的四元组。</p><p><strong>注意：</strong>答案中不可以包含重复的四元组。</p><p> </p><p><strong>示例 1：</strong></p><pre><strong>输入：</strong>nums = [1,0,-1,0,-2,2], target = 0<strong><br />输出：</strong>[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]</pre><p><strong>示例 2：</strong></p><pre><strong>输入：</strong>nums = [], target = 0<strong><br />输出：</strong>[]</pre><p> </p><p><strong>提示：</strong></p><ul>	<li><code>0 <= nums.length <= 200</code></li>	<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>	<li><code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code></li></ul>

以下程序实现了这一功能，请你填补空白处内容：

```cpp
class Solution
{
public:
	vector<vector<int>> fourSum(vector<int> &nums, int target)
	{
		long long l_target = target;
		sort(nums.begin(), nums.end());
		vector<vector<int>> results;
		int N = nums.size();
		for (int i = 0; i < N - 3; i++)
		{
			if (i > 0 && nums[i] == nums[i - 1])
				continue;
			for (int j = i + 1; j < N - 2; j++)
			{
				if (j > i + 1 && nums[j] == nums[j - 1])
					continue;
				for (int k = j + 1, l = N - 1; k < l; k++)
				{
					if (k > j + 1 && nums[k] == nums[k - 1])
						continue;
					_____________________________;
					if (k >= l)
					{
						break;
					}
					if ((target - nums[i] - nums[j] - nums[k] - nums[l]) == 0)
					{
						results.emplace_back(
							vector<int>({nums[i], nums[j], nums[k], nums[l]}));
					}
				}
			}
		}
		return results;
	}
};
```

## template

```cpp
class Solution
{
public:
	vector<vector<int>> fourSum(vector<int> &nums, int target)
	{
		long long l_target = target;
		sort(nums.begin(), nums.end());
		vector<vector<int>> results;
		int N = nums.size();
		for (int i = 0; i < N - 3; i++)
		{
			if (i > 0 && nums[i] == nums[i - 1])
				continue;
			for (int j = i + 1; j < N - 2; j++)
			{
				if (j > i + 1 && nums[j] == nums[j - 1])
					continue;
				for (int k = j + 1, l = N - 1; k < l; k++)
				{
					if (k > j + 1 && nums[k] == nums[k - 1])
						continue;
					while (k < l &&
						   (l_target - nums[i] - nums[j] - nums[k] - nums[l]) < 0)
					{
						l--;
					}
					if (k >= l)
					{
						break;
					}
					if ((target - nums[i] - nums[j] - nums[k] - nums[l]) == 0)
					{
						results.emplace_back(
							vector<int>({nums[i], nums[j], nums[k], nums[l]}));
					}
				}
			}
		}
		return results;
	}
};
```

## 答案

```cpp
while (k < l && (l_target - nums[i] - nums[j] - nums[k] - nums[l]) < 0)
{
	l--;
}
```

## 选项

### A

```cpp
while (k > l && (l_target - nums[i] - nums[j] - nums[k] - nums[l]) < 0)
{
	l--;
}
```

### B

```cpp
while (k > l && (l_target - nums[i] - nums[j] - nums[k] - nums[l]) < 0)
{
	l++;
}
```

### C

```cpp
while (k < l && (l_target - nums[i] - nums[j] - nums[k] - nums[l]) < 0)
{
	l++;
}
```