在一个数列中寻找两个数2sum、三个数3sum、四个数4sum分别求和等于目标式

2sum:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解答过程:

vector<int> twoSum(vector<int>& nums, int target) {
	unordered_map<int, int> hash;//用来存储已经检测过的数字
	vector<int> ret;
	for (int i = 0; i < nums.size(); ++i) {
		//判断numToFind是否在hash容器中
		if (hash.find(target - nums[i]) != hash.end()) {
			ret.push_back(hash[target - nums[i]]);
			ret.push_back(i);
			return ret;
		}
		hash[nums[i]] = i;
	}
	return ret;
}

3sum:

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
解答代码(此想法受启发于4sum的解答过程)
vector<vector<int>> threeSum(vector<int>& num) {
	sort(num.begin(), num.end());//从小到大进行排序
	vector<vector<int>> ret;
	int target = INT_MIN;
	int sec, thi;
	for (int i = 0; i < num.size(); ++i) {
		while (target == -num[i]) ++i;//避免重复值
		target = -num[i];
		sec = i + 1;
		thi = num.size() - 1;
		vector<int> tmp(1, num[i]);
		while (sec < thi) {//从num[sec]和num[thi]往中间夹,观察和值与target比较,进行变换sec和thi的值
			if (num[sec] + num[thi] < target) {//从前面递增
				while (num[sec] == num[sec+1]) ++sec;//避免重复值
				++sec;
			}
			else if (num[sec] + num[thi] > target) {//从后面递减
				while (num[thi] == num[thi - 1]) --thi;//避免重复值
				--thi;
			}
			else {
				tmp.push_back(num[sec]);
				tmp.push_back(num[thi]);
				ret.push_back(tmp);
				//target不变,继续将sec和thi往中间夹
				tmp.clear();
				tmp.push_back(num[i]);
				while (num[sec] == num[sec+1]) ++sec;//避免重复值
				++sec;
				while (num[thi] == num[thi - 1]) --thi;//避免重复值
				--thi;
			}
		}
	}
	return ret;
}

4sum:

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
解答过程采用olivier.valery的代码,如下所示,
vector<vector> fourSum(vector& nums, int target) {

	std::unordered_set <std::string> myset;
	vector<vector<int>> res;
	int n = nums.size();
	if (n<4)
		return res;
	sort(nums.begin(), nums.end());

	for (int i = 0; i<nums.size() - 3; i++) {
		int target2 = -nums[i];
		for (int j = i + 1; j<nums.size() - 2; j++) {
			int target3 = -nums[j];
			int ptr1 = j + 1;
			int ptr2 = nums.size() - 1;
			while (ptr1<ptr2) {
				int sum = nums[ptr1] + nums[ptr2] - target2 - target3;
				if (sum == target) {
					vector<int> temp;
					temp.push_back(nums[i]);
					temp.push_back(nums[j]);
					temp.push_back(nums[ptr1]);
					temp.push_back(nums[ptr2]);
					string s = to_string(nums[i]) + to_string(nums[j]) + to_string(nums[ptr1]) + to_string(nums[ptr2]);

					if (myset.find(s) == myset.end()) {
						myset.emplace(s);
						res.push_back(temp);
					}


					while (nums[ptr1] == temp[0])
						ptr1++;
					while (nums[ptr2] == temp[1])
						ptr2--;
					ptr1++;
				}
				else {
					if (sum>target)
						ptr2--;
					else
						ptr1++;

				}
				// Processing duplicates of Number 1
				while (i + 1 < nums.size() && nums[i + 1] == nums[i])
					i++;
			}
		}
	}
	return(res);
}
声明:以上题目来源于leetcode,解题思路来自网络上各位编程爱好者。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将n个数求和sum改造成递归函实现,可以按照以下步骤进行: 1. 定义递归函sum_recursive(n, nums),其n表示当前需要求和个数,nums表示待求和数列。 2. 当n=1时,直接返回nums[0]。 3. 当n>1时,将nums分为部分,分别递归求和,然后将部分的和相加即可。具体实现如下: ``` def sum_recursive(n, nums): if n == 1: return nums[0] else: mid = n // 2 left_sum = sum_recursive(mid, nums[:mid]) right_sum = sum_recursive(n - mid, nums[mid:]) return left_sum + right_sum ``` 这样,就可以将n个数求和sum改造成递归函实现了。 ### 回答2: 将求和sum改造成递归函实现的方法如下: 递归函的基本思想是将规模较大的问题拆分成规模较小相似的子问题,然后通过递归调用解决子问题,并将其结果进行累加,最终得到整个问题的解。 在本题,我们需要计算给定的n个数的和。首先,我们需要考虑递归函的终止条件。当n为1时,即只剩下一个,直接返回该即可。然后,我们可以将问题拆分成个子问题:求前n-1个数的和和第n个数,然后将个结果进行相加即可得到n个数的和。 具体的递归函实现如下: ```python def sum_recursive(nums, n): if n == 1: return nums[0] else: return nums[n-1] + sum_recursive(nums, n-1) ``` 其,nums为存储字的列表,n为列表字的个数。当n为1时,直接返回列表唯一的字;否则,返回最后一个字加上前n-1个数字的和。 以上就是将求和sum改造成递归函实现的方法。通过递归调用,可以不断缩小问题的规模,最终得到所有字的和。 ### 回答3: 将求和sum改造为递归函的过程如下: 我们需要定义一个递归函来完成这个任务,我们将其命名为recursive_sum。这个函将有个参一个n和一个列表nums。 1. 首先,我们需要判断递归的结束条件。当n等于0时,说明已经将所有的相加完毕,此时我们返回0,并结束递归。 2. 否则,我们将获取列表的第n个数,即nums[n-1],并将其与递归调用recursive_sum的结果相加。这样就实现了将前n-1个数的和与第n个数相加的效果。 3. 最后,我们将这个结果作为递归函的返回值。 通过这样的递归调用,我们可以将求和问题分解为不断地将前一个的和与下一个相加的过程,直到将全部相加完毕并返回最终的和。 下面是一个示例代码实现: ```python def recursive_sum(n, nums): if n == 0: return 0 else: return nums[n-1] + recursive_sum(n-1, nums) ``` 这个递归函的时间复杂度为O(n),其n是列表nums的长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值