问题:
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.