解决方案应该是递归的,零是任何集合中的一个元素,并且可以多次使用集合中的元素。递归确定是否存在与给定的int参数匹配的正整数数组的子集和?
例如,如果数组为{3,5,7},则17将返回true,因为5 + 5 + 7 = 17 但4将返回false。
我已经试过这样:
public static boolean isSumOf(int [] s, int n)
{
return isSumOf(s, s.length, n);
}
static boolean isSumOf(int s[], int length, int n)
{
// Base Cases
if (n == 0)
{
return true;
}
if (length == 0 && n != 0)
{
return false;
}
// If last element is greater than sum, then ignore it
if (s[length-1] > n)
{
return isSumOf(s, length-1, n);
}
/* else, check if sum can be obtained by any of the following
(a) including the last element
(b) excluding the last element */
return isSumOf(s, length-1, n) || isSumOf(s, length-1, n-s[length-1]);
}
,但它排除了多次
我忘了说,我不允许使用循环,但它的一个有趣的方向... –
看到更新..... – MBo
哇,我不敢相信!我正在努力解决这个问题......非常感谢你! –