问题
In my question, we are given a number and list of numbers and we are supposed to get the first number from the given list of numbers by using the operations + or -
For Example: -1 is the target number 1 2 3 5 are numbers given to get -1 solution should be -1+2+3-5 = -1 or -1-2-3+5 = -1
Limits for target number is from -180 to +180 and the limit for list of numbers is from 2 to 20
To find the solution what kind of algorithm should be used? If I want to use generate all the possibilities will it be efficient? And is the any binary solution of this problem?
Thanks for your help
回答1:
Number of possibpe variants is 2^20
; Let's generate all numbers from 0
to 2^N
. Binary representation of these numbers will be 00000(20 zeroes), 000...01,0000.10,...,1111(20 ones). Imagine, that each zero is minus and one is a plus.
int target = -1;
int[] numbers = new int[20];
Arrays.fill(numbers, 0);
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 5;
for(int i=0;i<(1<<20);i++) //masks from 00...00 to 11...11 (from --...--- to ++...+++)
{
int sum=0;
for(int bit=0;bit<20;bit++)
{
if(((1<<bit)&i)>0)
{
sum+=numbers[bit];
}
else
{
sum-=numbers[bit];
}
}
if(sum==target)
{
System.out.print(target+" = ");
for(int bit=0;bit<20;bit++)
{
if(((1<<bit)&i)>0)
{
System.out.print("+"+numbers[bit]);
}
else
{
System.out.print("-"+numbers[bit]);
}
}
break;
}
}
Output: -1 = -1+2+3-5-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0
来源:https://stackoverflow.com/questions/18586154/how-to-get-a-number-from-a-list-of-numbers-by-using-or-operations