[英]subset sum find all subsets that add up to a number
我一直在学习动态编程,我想通过打印出所有加起来数字的子集来进一步考虑经典子集和问题。 我到底该怎么做呢? 截至目前,我知道如何根据是否有一个加起来的子集来打印真或假
public static boolean hasSum(int [] array, int sum)
{
int len = array.length;
boolean[][] table = new boolean[sum+1][len+1];
int i;
for( i = 0; i <= len; i++ )
table[0][i] = true;
for( i = 1; i <= sum; i++ )
table[i][0] = false;
for( i = 1; i <= sum; i++ )
{
for( int j = 1; j <= len; j++ )
{
table[i][j] = table[i][j-1];
if( !table[i][j] && i >= array[j-1] )
table[i][j] = table[i-array[j-1]][j-1];
}
}
return table[sum][len];
}
如果可能的话,我想返回所有子集的数组。
这个问题比原来的问题更难。
对于您设置为true
每个table[i][j]
,您必须标记其所有前任,即所有table[i1][j1]=true
,因为您将table[i][j]
标记为true。 这样你就可以构建一种图形结构。 该图的顶点是对(i,j)
。
然后,当你想打印答案时,你必须追溯从(i,j)
到所有可能的(i1,j1)
等等。 对于这个,只是一个数组是不够的,你需要额外的/辅助数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.