有序9位数问题的算法是什么?

问题描述 投票:0回答:2

给出任意3位N作为输入,

我们只能使用1到9之间的数字,以使顺序永不中断,并且不会重复任何数字。

例如

If N = 150. 
123 + 4 + 5 - 6 + 7 + 8 + 9 = 150

我们可以组合数字并插入'-''+'操作以获得所需的N值。

algorithm math digits
2个回答
2
投票

排列数字:1 2 3 4 5 6 7 8 9。这些数字之间有8个空格。每个空格可以是'+'或'-'或空格(将数字连在一起)。因此,您可以使用3 ** 8,即6561种不同的可能操作组合。这足够小,可以循环尝试所有这些文件并检查哪一个有效。


0
投票

您可以这样操作(此代码由python编写:

N = 150
digit_from, digit_to = 1, 9    ### from 1 to 9 ###

def find(N, pos, equation, num, coff):

    if pos > digit_to:
        if N - coff * num == 0:
            print(equation)
    else:
        find( N-coff*num, pos+1, equation+'+'+str(pos), pos, 1 )   ### plus  ###
        find( N-coff*num, pos+1, equation+'-'+str(pos), pos, -1 )  ### minus ###
        find( N, pos+1, equation+str(pos), num*10+pos, coff )      ### blank ###
    return

find( N, digit_from + 1, '150 = 1', digit_from, 1 )

结果(如果N = 150且数字在1到9之间):

150 = 1+23+45-6+78+9
150 = 1+234+5+6-7-89
150 = 1-2+3-4+56+7+89
150 = 12+3+45-6+7+89
150 = 123+4+5-6+7+8+9
150 = 123+45+6-7-8-9
150 = 123-4-56+78+9

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.