简体   繁体   English

此递归算法有什么好的迭代解决方案?

[英]What is a good iterative solution for this recursive algorithm?

Problem : Given an array and a target number, print the number of ways the target number can be written as a unique combination of elements in the array. 问题 :给定一个数组和一个目标编号,以数组中元素的唯一组合形式打印目标编号的书写方式

Example : 范例

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

Recursive Solution 递归解

F(4) = F(4-1) + F(4-2) + F(4-3)
F(4) = F(3) + F(2) + F(1)
...

Total sum is the sum of each recursive call to the function with the array value subtracted as the argument. 总和是对函数的每个递归调用的总和,其中减去数组值作为参数。

Conceptually recurrence can be expressed as (ironically as an iteration): 从概念上讲,递归可以表示为(讽刺地表示为迭代):

for(int i=0; i<array.length; i++)
   sum+=F(target - array[i]);

Base Cases: 基本案例:

F(0) = 1 //Implies sums to target
F(<0) = 0 //Implies cannot sum to target

However, even for a trivial case as above, it results in a StackOverflowError. 但是,即使对于上面的琐碎情况,也会导致StackOverflowError。 How best to iterate the solution below: 如何最好地迭代以下解决方案:

Code

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));
    }

}

Pseudo Code 伪码

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];

Here is a solution in Python. 这是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.

相关问题 寻找一个递归的迭代解决方案 - Looking for an iterative solution of a recursive one 迭代和递归解决方案的时间复杂度 - Time complexity on iterative and recursive solution 自适应正交算法-递归迭代 - Adaptive Quadrature Algorithm - Recursive to Iterative 将递归Diff算法转换为迭代算法的建议? - Advice converting recursive Diff Algorithm to an iterative one? 插入排序算法的大小:迭代和递归 - Big o of insertion sort algorithm: iterative and recursive 需要帮助来确定给定算法是迭代还是递归 - Need help to determine if a given algorithm is iterative or recursive 用于查找数组中最大数的递归算法的运行时间复杂度是多少。 比较它与迭代循环代码 - What will be the run time complexity for recursive algorithm for finding the largest number in an array. Compare it vs iterative loop code 编写一个迭代算法递归,但我不明白我做错了什么 - Writing an iterative algorithm recursive, but I don´t see what Im doing wrong Java 类似 MathPow 的方法在效率上具有迭代和递归的解决方案-作业 - Java method like MathPow with a solution iterative and recursive in efficiency-Homework 调用notifyAll的最佳解决方案是什么? - What is the good solution for calling notifyAll?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM