Arrays 在数组中查找N个和为0的数字子集[子集和问题,返回子集]

Arrays 在数组中查找N个和为0的数字子集[子集和问题,返回子集],arrays,dynamic,dynamic-programming,Arrays,Dynamic,Dynamic Programming,我正在练习标题中的面试问题 对于那些直接想知道我的问题的人,请跳到“我的问题的小版本” 有关更多上下文,请继续阅读 =>对于N=2, 我们可以简单地使用地图 =>对于N=3, 有一个n^2解决方案: [检查接受的答案,它实际上为您提供了一个总和为0的解决方案,而不是链接标题中的总和] 我想通过上面的链接,我们可以得到3个N=4的指针,得到一个N^3的解 无论如何,我要指出的是,最终所有这些解决方案都不会随着N的增长而扩展。所以我在寻找一个通用的解决方案 我认为这可以从一个子集和问题中得到。但是,

我正在练习标题中的面试问题

对于那些直接想知道我的问题的人,请跳到“我的问题的小版本”

有关更多上下文,请继续阅读

=>对于N=2, 我们可以简单地使用地图

=>对于N=3, 有一个n^2解决方案: [检查接受的答案,它实际上为您提供了一个总和为0的解决方案,而不是链接标题中的总和]

我想通过上面的链接,我们可以得到3个N=4的指针,得到一个N^3的解

无论如何,我要指出的是,最终所有这些解决方案都不会随着N的增长而扩展。所以我在寻找一个通用的解决方案

我认为这可以从一个子集和问题中得到。但是,此问题的解决方案[动态编程版本]返回布尔值。我希望得到实际的子集。
布尔解本身并不是完全自然地推导出来的[从这个意义上说,除非你读过它,否则你不能轻易地“推导”出答案..我必须写下一个例子来理解它]。无论如何,我正在寻找一种方法来修改它,给我一个子集,而不仅仅是一个布尔值

我问题的小版本:
修改此选项以返回实际子集,而不仅仅是布尔值

Let S[i] = true if we can make sum i and false otherwise.

S[0] = true // we can always make sum 0: just don't choose any number
S[i] = false for all i != 0
for each number i in your input
    for s = MaxSum downto i
        if ( S[s - i] == true )
            S[s] = true; // if we can make the sum s - i, we can also make the sum s by adding i to the sum s - i.

只要在可能的情况下,让
S[S]
包含构成该总和的数字列表:

Let S[i] = the list of numbers that make up that sum and false (or null, something distinct from an empty list) otherwise.

S[0] = empty list // we can always make sum 0: just don't choose any number
S[i] = null for all i != 0
for each number i in your input
    for s = MaxSum downto i
        if ( S[s - i] != null )
            S[s] = S[s-i] with i added; // if we can make the sum s - i, we can also make the sum s by adding i to the sum s - i.

只要在可能的情况下,让
S[S]
包含构成该总和的数字列表:

Let S[i] = the list of numbers that make up that sum and false (or null, something distinct from an empty list) otherwise.

S[0] = empty list // we can always make sum 0: just don't choose any number
S[i] = null for all i != 0
for each number i in your input
    for s = MaxSum downto i
        if ( S[s - i] != null )
            S[s] = S[s-i] with i added; // if we can make the sum s - i, we can also make the sum s by adding i to the sum s - i.

谢谢非常优雅。所以基本上我在java中的结构是List。除了我认为java不允许混合集合和泛型数组之外,所以
int[][]]
List
谢谢。。非常优雅。所以基本上我在java中的结构是List。除了我认为java不允许混合集合和泛型数组之外,所以
int[][]]
List