Total of all numbers from 1 to N will always be zero

rob*_*ert 6 java algorithm

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
Run Code Online (Sandbox Code Playgroud)

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..

hol*_*fun 10

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

我使用Python进行了快速实现,但是将其轻松转移到Java或您正在使用的任何对象都应该很容易。

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)
Run Code Online (Sandbox Code Playgroud)

希望你能明白。

  • 您实际上无法使用此方法返回任何内容,例如:output`String`。 (2认同)