陷入组合问题
我的程序有问题。我提取了一组数据,我想测试是否存在特定数字的组合。例如,我有一个 int 数组,1 2 3 4 5,我想知道是否有 7 的组合,它必须回答是,有 3 + 4。
我发现我需要使用组合公式。所以我认为外循环可能会像5C1..5C2..5C3..etc一样,开始一次“取1”然后“取2”以找出所有可能的组合。问题是我不知道如何在实际代码中实现这一点。
我不太擅长数学,定义的循环结构确实会有帮助。
预先非常感谢!
I'm having a problem w/ my program. I have extracted a set of data and I would like to test if there is a combination for a particular number. For example, I have an array of int, 1 2 3 4 5, I would like to know if there is a combination for 7 maybe, and it must answer yes there is 3 + 4.
I figured out that I need to use the combination formula. So I thought that the outer loop may go like 5C1..5C2..5C3..etc, starting to "take 1" then "take 2" at a time to find out all the possible combinations. The problem is I'm stuck at how to implement this in actual codes.
I'm not really very good with Math, A defined loop structure would really help.
Thanks a lot in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是从整数列表中获取所有可能总和的方法:
用法:
输出:
虽然这个解决方案不会给出您得出总和的操作数,它将包括从
1
到1 + 2 + 3 + 4 + 5 + 6
的任何内容Here is a method that gets all possible sums from a List of Integers:
Usage:
Output:
While this solution won't give you the operands that lead to the sum, it will include anything from
1
to1 + 2 + 3 + 4 + 5 + 6
对于这个问题有一个简单的伪多项式时间动态规划,首先确定是否可以丰富
1
然后对于 sum2
我们有两个选择,使用数组项之一,或者使用先前创建的1
与新元素相加,您可以完成这个二维表直至丰富所要求的数字:这是O(n*Sum)。事实上,检查
O(n*given_number)
就足够了。There is a simple pseudo polynomial time dynamic programming for this problem, first determine is possible to rich
1
then for sum2
we have two option, use one of a array items, or use previous founded1
add up with new element, you can complete this 2 dimensional table upto rich the requested number:This is O(n*Sum). in fact is enough to check to
O(n*given_number)
.一个快速但肮脏的解决方案可能是创建一个二维数组,其索引(在两个维度上)是数组中数字的位置,值是组合。像这样的事情:
如果您现在想要找到 6 的组合,您可以检查所有值并获取等于 6 的值的 x 和 y 索引。(在示例中:0/2、1/1 和 2/ 0)。然后在原始数组中查找这些索引处的数字(例如0/2 -> 1 和5、1/1 -> 3 和3、2/0 -> 5 和1)。
请注意,这是一种快速且性能不佳的方法(尤其是对于较大的数组),并且可能返回比您想要或需要的更多的排列(0/2 和 2/0 对于操作
add
是相同的)。然而,这应该适用于许多可能的操作,例如 xy 对于 x=1, y=5(结果:1)和 x=5, y=1(结果:5)会有所不同。A quick and dirty solution might be to create a 2D-Array whose index (in both dimensions) is the position of the number in the array and the values are the combinations. Something like this:
If you now want to find the combinations for 6, you could check all values and get the x and y indices for values that are equal to 6. (In the example: 0/2, 1/1 and 2/0). Then lookup the numbers at those indices in the original array (e.g. 0/2 -> 1 and 5, 1/1 -> 3 and 3, 2/0 -> 5 and 1).
Note that this is a quick and quite imperformant way (especially for bigger arrays) and might return more permutations than you want or need (0/2 and 2/0 is the same for operation
add
). However, this should work for many possible operations, e.g. xy would be different for x=1, y=5 (result: 1) and x=5, y=1 (result: 5).