【问题标题】:Recursion returning all matching answers递归返回所有匹配的答案
【发布时间】:2016-08-17 20:16:42
【问题描述】:

您好,我正在使用递归,如下所示。

public static int match(int[][] mat , int count)
    {

        boolean isComplete = true;
        for(int i=0;i<mat.length;i++)
        {
            for(int j=0;j<mat[i].length;j++)
            {
                if(mat[i][j] == 0)
                {
                    isComplete = false;
                    count++;
                    ArrayList<int[][]> mMats =  getMats(mat, i, j);
                    for(int k=0;k<mMats.size();k++)
                    {
                        match(mMats.get(k), count);
                    }
                }
            }

        }
        if(isComplete)
        {
            System.out.println(count);
            return count;

        }
        else
        {
            return 0;
        }
    }

我想要实现的是,如果我们到达 isComplete 块,它应该返回我那个特定的计数。我不想要其他计数,现在函数返回许多计数如何解决这个问题。谢谢。

【问题讨论】:

  • 该函数正在打印多个计数,因为每次递归运行该函数时都可以调用if(isComplete)。如果您只想要总计数,您可以从第一次调用 match 函数的任何位置打印返回值。

标签: java recursion return


【解决方案1】:

如果递归调用返回的不是0,您可以停止迭代。即,当找到第一个匹配项时:

...
for(int k=0;k<mMats.size();k++) {
    int ret = match(mMats.get(k), count);
    if(ret != 0)
        return ret;
}
...

【讨论】:

  • 为了解决我已经取了 0 实际上任何数字都可以在 0 的位置给出。
  • @Crazy 你返回了一个计数,我认为它应该是正数。所以你可以返回 -1 而不是 0 并检查它。
猜你喜欢
  • 2021-07-20
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-19
  • 2018-05-30
  • 2023-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多