【发布时间】:2014-06-28 14:31:36
【问题描述】:
问题:给定一个数组和一个目标数,打印出方法数目标数可以写成数组中元素的唯一组合。 p>
示例:
array = {1,2,3} target = 4
4 = {2,2}, {3,1}, {1,1,1,1} //numbers can be repeatedly selected from the array.
Ans: 3 ways
递归解决方案
F(4) = F(4-1) + F(4-2) + F(4-3)
F(4) = F(3) + F(2) + F(1)
...
总和是每次递归调用函数的总和,减去数组值作为参数。
从概念上讲,递归可以表示为(具有讽刺意味的是一次迭代):
for(int i=0; i<array.length; i++)
sum+=F(target - array[i]);
基本案例:
F(0) = 1 //Implies sums to target
F(<0) = 0 //Implies cannot sum to target
然而,即使是上述的一个小例子,它也会导致 StackOverflowError。如何最好地迭代以下解决方案:
代码
public class CombinationSum {
private int[] array;
private int target;
public CombinationSum(int[] array, int target)
{
this.array = array;
this.target = target;
}
public int recurSum(int val)
{
int sum = 0;
if(val < 0 )
return 0;
else if(val == 0)
return 1;
else
{
for(int i = 0; i<array.length; i++)
{
sum+= recurSum(target-array[i]); //heavy recursion here?
}
return sum;
}
}
public static void main(String[] args)
{
int target = 4;
int[] array = {1,2,3};
CombinationSum cs = new CombinationSum(array, target);
System.out.println("Number of possible combinations: "+cs.recurSum(target));
}
}
【问题讨论】:
-
只需将值存储在一个数组中,然后在数组中查找而不是重新计算。
-
sum+= recurSum(target-array[i]);它应该是 sum+= recurSum(val-array[i]);
标签: java algorithm recursion iteration