考虑源代码:
public class subSetSumR {
// Solving Subset sum using recursion
// Programmed by Fuentes, Feb. 9, 2009
// Subset sum consists of finding a subset of mySet whose elements add up to goal
// It is a well-known NP-complete problem
public static boolean subSetSumRecur (int[] mySet, int n, int goal) {
if (goal == 0) return true;
if ((goal < 0) | (n >= mySet.length)) return false;
if (subSetSumRecur(mySet, n + 1, goal - mySet[n])) {
System.out.print(mySet[n] + " ");
return true;
}
if (subSetSumRecur(mySet, n + 1, goal)) return true;
return false;
}
}
重要事实:输入数量大于1如何使用此事实来加速上述解决方案?
答案 0 :(得分:2)
set = emptyset; for(num : array_of_number) { newset = emptyset; for(item : set) { if(num + item == goal) return ""we found it"; newset.insert(num + item); } set.insert(newset); } return "Not possible";
记忆化
set<tuple<int, int>> memo; // Make sure to clear before calling your function
public static boolean subSetSumRecur (int[] mySet, int n, int goal) {
if( set.contains( tuple(n, goal) ) return false;
set.insert( tuple(n, goal) );
...
... /* Your code goes here */
...
}
在java中应该有类似于set(我认为是hashset)和tuple(在C ++中std :: pair是最好的选择。如果在java中没有类似的东西你可以创建一个包含2个可插入的int的小类到一个哈希集)。