【发布时间】:2017-06-14 07:17:13
【问题描述】:
解决方案应该是递归的,零是任何集合的元素,关键是你可以多次使用集合的元素。
例如,如果数组是 {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]);
}
但它排除了多次添加元素的能力
【问题讨论】:
标签: java arrays algorithm recursion backtracking