求和为某个值得全部序列

问题:

Write a function that takes an array of five integers, each of which is between 1 and 10, and returns the number of combination of those integers that sum to 15. For example, calling the function with the array [1, 2, 3, 4, 5] should return 1, while calling it with [5, 5, 10, 2, 3] should return 4 (5 + 10, 5 + 10, 5 + 5 + 2 + 3, 10 + 2 + 3).

分析:

组合问题。

int ExpectedSumSequence(int* pData, int len, int sum){
	int seqCount = 0;
	if (len==0 && sum==0){
		seqCount = 1;
	} else if (len>0){
		//序列数目是第一个元素包含在序列中的序列数和第一个元素不包含在序列中的序列数之和
		seqCount = ExpectedSumSequence(pData+1, len-1, sum-pData[0])+ExpectedSumSequence(pData+1, len-1, sum);
	}
	return seqCount;
}


如果还需要打印出所有符合条件的序列:

static int ExpectedSumSequence(int* pData, int start, int end, bool contained[], int expectedSum){
	int seqCount = 0;
	if (start==end && expectedSum==0){
		seqCount = 1;
		for (int i=0; i<end; i++){
			if (contained[i])
				cout<<pData[i]<<" ";
		}
		cout<<endl;
	} else if (start<end){
		//第一个元素包含在序列中的序列数
		contained[start] = true;
		seqCount = ExpectedSumSequence(pData, start+1, end, contained, expectedSum-pData[start]);
		//第一个元素不包含在序列中的序列数
		contained[start] = false;
		seqCount += ExpectedSumSequence(pData, start+1, end, contained, expectedSum);
	}
	return seqCount;
}
int ExpectedSumSequence(int* pData, int len, int sum){
	bool* contained = new bool[len];	//contained[i]表示第i个元素在不在序列中
	int seqCount = ExpectedSumSequence(pData, 0, len, contained, sum);
	return seqCount;
}

问题:

Given a set of n integers, each in the range 0 : : :K, partition the integers into two subsets to minimize |S1-S2|, where S1 and S2 denote the sums of the elements in each of the two subsets.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值