从1到N的所有数字的总和始终为零 [英] Total of all numbers from 1 to N will always be zero

查看:96
本文介绍了从1到N的所有数字的总和始终为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我必须打印从 1到N
数字序列的所有组合,这些组合将始终为零。
允许插入 + (用于加法)和- (用于减法)在每个
数字之间,以使结果为零。

The problem is I have to print all combinations of a sequence of numbers from 1 to N that will always result to zero. It is allowed to insert "+" (for adding) and "-" (for subtracting) between each numbers so that the result will be zero.

//Output
N = 7

1 + 2 - 3 + 4 - 5 - 6 + 7 = 0
1 + 2 - 3 - 4 + 5 + 6 - 7 = 0
1 - 2 + 3 + 4 - 5 + 6 - 7 = 0
1 - 2 - 3 - 4 - 5 + 6 + 7 = 0

那么我该如何实现呢?我并不是在要求实际的
代码来执行此操作,而只是提示和想法来解决
要做的事情。谢谢。

So how can I implement this? I am not asking for the actual codes to do this, just a hint and ideas to solve this will do. Thank you..

推荐答案

您还可以在此处使用递归。只要记住您当前的整数,您的最大整数,您的当前总和以及某种运算历史(也可以是您的最终序列)即可。
在每个级别中,您都按照两个方向进行操作:将总和加减。

You could also use recursion here. Just remember your current integer, your max integer, your current sum and some kind of history of operations (could also be your final sequence). In every level you proceed the path in two dirdctions: adding to your sum and substracting from it.

我在Python中做了一个快速实现,但是应该很容易将其转移到Java或您正在使用的任何内容。

I did a quick implementation in Python, but it should be easy to transfer this to Java or whatever you are using.

def zero_sum(curr, n, seq, sum):
    if curr == n and sum == 0:
        print(seq)
    elif curr < n:
        zero_sum(curr + 1, n, seq + " - " + str(curr + 1), sum - (curr + 1))
        zero_sum(curr + 1, n, seq + " + " + str(curr + 1), sum + (curr + 1))

zero_sum(1, 7, "1", 1)

希望您能明白。

这篇关于从1到N的所有数字的总和始终为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆