[英]What is a good iterative solution for this recursive algorithm?
問題 :給定一個數組和一個目標編號,以數組中元素的唯一組合形式打印目標編號的書寫方式 。
范例 :
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));
}
}
偽碼
F[0]=1;
for(i=1;i<=n;++i){
F[i]=0;
for(j=1;j<i++j){
F[i]+=F[i-j];
}
}
print F[n];
這是Python中的解決方案。
#input is a list A of positive integers, and a target integer n
#output is a list of sublists of A (repeats OK!) with sum n
#permutations will appear
def make_list(A,n):
A = list(set(A)) #eliminate repeats in A
L = []
if n > 0:
for a in A:
if type(make_list(A,n-a)) == list:
for l in make_list(A,n-a):
l.append(a)
L.append(l)
elif n == 0:
L = [[]]
else: L = -1
return L
#returns the count of distinct lists in make_list(A,n)
def counter(A,n):
b = []
for l in make_list(A,n):
if sorted(l) not in b:
b.append(sorted(l))
return len(b)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.