【 Algorithm】排序数组中查找和为n的一对数和所有组合

本文介绍两种算法,一种是在有序数组中寻找两数之和等于特定值的方法,使用双指针技巧;另一种是解决背包问题的递归方法,找出数组中多个数的组合使其总和等于给定值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*************************************************
题目:11.	递增数组中查找和为n的一对数
思路:设置头尾指针,比较两者指向的数之和与sum的大小

****************************************************/
#include"stdafx.h"
#include<iostream>
using namespace std;

bool FindNums(int arr[],int len,int sum)
{
	bool notfound = true;
	if(arr == NULL || len <1)
		return notfound;
	int *pHead = arr;
	int *pLast = arr+len-1;
	while(pHead < pLast)
	{
		long long cursum = *pHead + *pLast;
		if(cursum == sum)
		{
			notfound =true;
			cout << *pHead <<" "<<*pLast <<endl;
			break;
		}
		else if(cursum < sum)
		{
			pHead++;
		}
		else
			pLast--;
	}
	return notfound;
}
int main()
{
	int arr[8] = {1,3,4,5,6,8,11,13};
	int sum = 18;
	 cout << FindNums(arr,8,18) << endl;
	 system("pause");
	 return 0;

}
</pre><pre name="code" class="cpp">/******************************数组——背包问题*************************************** 
	题目:求数组和为定值n的m个数
	思路:典型的背包问题
	 采用
**********************************************************************/  
#include"stdafx.h"
#include<iostream>
#include<assert.h>
#include<list>
using namespace std;

list<int> ilist;

void Find_factor(int sum,int n)
{
	//递归出口
	if(sum <= 0|| n <= 0)
		return ;
	if(sum == n)//要放的数刚好是满足条件的最后一个数
	{
		for(list<int>::iterator iter = ilist.begin(); iter != ilist.end(); iter++)
			cout << *iter << "+";
		cout << n <<endl;
	}
	ilist.push_back(n);
	Find_factor(sum-n,n);
	ilist.pop_back();
	Find_factor(sum,n-1);
}


int main()
{
	int sum, n;
	cout << "请输入你要等于多少的数值 sum:" << endl;
	cin >> sum;
	cout << "请输入你要从 1.....n 数列中取值的 n:" << endl;
	cin >> n;
	cout << "所有可能的序列,如下:" << endl;
	Find_factor(sum,n);

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值