2d子集和的动态规划解决方案

时间:2015-02-12 11:54:09

标签: algorithm

所以我有这个问题:给定{x,y}形式的一组二维元组,其中所有x和y都是正整数,决定是否可以取出一个子集,以便:

√( (∑x)² + (∑y)²) = A²

对于正整数A。

示例,给出 [{2,2},{1,4},{1,2}] and A = 5 一个解决方案是{2,2} and {1,2} since 3² + 4² = 5²

允许多次重用相同的元组。

目标是通过动态编程来解决这个问题。我在看http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/,这是一个子集和问题的动态解决方案;但是这里的区别在于所有术语都是平方和2d,所以我不相信这种方法有效

1 个答案:

答案 0 :(得分:1)

可能有更快的选项,但简单的PD是:

T(X,Y,i):是否有可能在第i个项中达到Σx= X和Σy= Y?

T(0, 0, 0) = TRUE
T(X, Y, i) = FALSE if X<0 or Y<0 or (i==0 and X!=0 and Y!=0)
T(X, Y, i) = T(X-V[i].X, Y-V[i].Y, i) or T(X, Y, i-1)

然后扫描每对(X,Y),找到一个X²+Y²=A²且T(X,Y,n)为真(其中n是集合的大小)。

这是一个非优化的递归版本,只是为了证明这个概念(在Python中):

def T(V, x, y, i):
    if x==0 and y==0 and i==0: return []
    if x<0 or y<0 or i<=0: return None

    answer = T(V, x-V[i-1][0], y-V[i-1][1], i)
    if answer is not None: return answer + [V[i-1]]
    return T(V, x, y, i-1)

def solve(V, A):
    for x in range(A):
        for y in range(A):
            if x*x+y*y==A*A:
                answer = T(V, x, y, len(V))
                if answer:
                    return answer
    return None

print(solve([(2,2),(1,4),(1,2)], 5))

它打印出一种可能的解决方案:

[(2, 2), (1, 2)]