首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对于这种递归算法,什么是好的迭代解决方案?

对于这种递归算法,什么是好的迭代解决方案?
EN

Stack Overflow用户
提问于 2014-05-11 03:17:01
回答 2查看 441关注 0票数 0

Problem:给定数组和目标号,打印目标数可以作为数组中元素的唯一组合的方式。

示例

代码语言:javascript
复制
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

递归解

代码语言:javascript
复制
F(4) = F(4-1) + F(4-2) + F(4-3)
F(4) = F(3) + F(2) + F(1)
...

总计和是对函数的每个递归调用的和,其中数组值减去作为参数。

概念上的重复可以表示为(具有讽刺意味的是,作为迭代):

代码语言:javascript
复制
for(int i=0; i<array.length; i++)
   sum+=F(target - array[i]);

基本案例:

代码语言:javascript
复制
F(0) = 1 //Implies sums to target
F(<0) = 0 //Implies cannot sum to target

但是,即使对于上面这样的简单情况,它也会导致一个StackOverflowError。如何最好地迭代下面的解决方案:

代码语言:javascript
复制
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));
    }

}
EN

回答 2

Stack Overflow用户

发布于 2014-05-11 03:24:24

伪码

代码语言:javascript
复制
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];
票数 0
EN

Stack Overflow用户

发布于 2014-05-12 19:29:16

下面是Python中的一个解决方案。

代码语言:javascript
复制
#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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23588527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档