如何通过使用+或获取的数号的列表 - 操作 [英] How to get a number from a list of numbers by using + or - operations
问题描述
在我的问题,我们得到了一些数字和名单,我们应该通过行动来得到的数字给定列表中的第一个号码+或 -
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 -
例如: -1是目标数 1 2 3 5号给得-1 解决办法应该是1 + 2 + 3-5 = -1 或-1-2-3 + 5 = -1
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
限值目标数是从-180至180和限制编号列表是从2至20个
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?
感谢您的帮助
推荐答案
的possibpe变种数量为 2 ^ 20
;让我们产生从 0
所有数字以 2 ^ N
。二进制重新$ P $这些数字psentation将是00000(20零),000 ... 01,0000.10,......,1111(20的)。试想一下,每个零为负,一个是一个加号。
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;
}
}
输出: -1 = 1 + 2 + 3-5-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0
Output: -1 = -1+2+3-5-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0
这篇关于如何通过使用+或获取的数号的列表 - 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!