【发布时间】:2013-03-27 19:07:41
【问题描述】:
这就是问题所在。
将给定数字 N 写为给定数字的总和,仅使用加法和减法。
这是一个例子:
N = 20
Integers = 8, 15, 2, 9, 10
20 = 8 + 15 - 2 + 9 - 10。
这是我的想法;
第一个想法是使用蛮力,交替加减。首先,我计算组合的数量及其 2^k(其中 k 是整数的数量),因为我只能交替使用减号和加号。然后我遍历从 1 到 2^k 的所有数字,并将其转换为二进制形式。对于任何 1,我使用加号,对于任何 0,我使用减号。通过一个示例(使用上面的示例),您会更容易理解。
The number of combinations is: 2^k = 2^5 = 32.
Now I run through all numbers from 1 to 32.
So i get: 1=00001, that means: -8-15-2-9+10 = -24 This is false so I go on.
2 = 00010, which means: -8-15-2+9-10 = -26. Also false.
这种方法效果很好,但是当整数数量太大时,它需要的时间太长。
这是我的 C++ 代码:
#include <iostream>
#include <cmath>
using namespace std;
int convertToBinary(int number) {
int remainder;
int binNumber = 0;
int i = 1;
while(number!=0)
{
remainder=number%2;
binNumber=binNumber + (i*remainder);
number=number/2;
i=i*10;
}
return binNumber;
}
int main()
{
int N, numberOfIntegers, Combinations, Binary, Remainder, Sum;
cin >> N >> numberOfIntegers;
int Integers[numberOfIntegers];
for(int i = 0; i<numberOfIntegers; i++)
{
cin >>Integers[i];
}
Combinations = pow(2.00, numberOfIntegers);
for(int i = Combinations-1; i>=Combinations/2; i--) // I use half of the combinations, because 10100 will compute the same sum as 01011, but in with opposite sign.
{
Sum = 0;
Binary = convertToBinary(i);
for(int j = 0; Binary!=0; j++)
{
Remainder = Binary%10;
Binary = Binary/10;
if(Remainder==1)
{
Sum += Integers[numberOfIntegers-1-j];
}
else
{
Sum -= Integers[numberOfIntegers-1-j];
}
}
if(N == abs(Sum))
{
Binary = convertToBinary(i);
for(int j = 0; Binary!=0; j++)
{
Remainder = Binary%10;
Binary = Binary/10;
if(Sum>0)
{
if(Remainder==1)
{
cout << "+" << Integers[numberOfIntegers-1-j];
}
else
{
cout << "-" << Integers[numberOfIntegers-1-j];
}
}
else
{
if(Remainder==1)
{
cout << "-" << Integers[numberOfIntegers-1-j];
}
else
{
cout << "+" << Integers[numberOfIntegers-1-j];
}
}
}
break;
}
}
return 0;
}
【问题讨论】:
-
请搜索现有的问题,因为我记得之前多次看到过这个问题。
-
正如 Ben 所说,这个(或类似的)已经被问过很多次了。
-
我看过您发布的所有示例,但我认为这有点不同。几乎每个示例都是子集问题。这个正在使用所有给定的数字并获得想要的数字。另外,我从来没有真正找到可以减去的例子。
-
为什么要将组合数转换为二进制并除以十进制的10?
标签: c++ binary numbers sum combinations