递归可能一开始很难理解,但是一旦你了解它就会很清楚。缺点是递归比基本的 for 循环 (Space complexity of recursive function) 需要更多的空间。对于某些问题,首先编写递归版本然后将其编写为 for-loop 会更容易。此外,如果空间不是问题,它有助于使您的代码干净(没有 for 循环!)
我做了一些基本的递归,至少为你写下的两个例子给出了正确的答案。我可能错过了一个边缘案例:编写每个函数调用和一些(前卫的)测试用例可能是一个好习惯。
public int recursiveWrapper(int n, int max) {
return recursive(n, max, 1, 1);
}
public int recursive(int n, int max, int lower, int current) {
// // for your convenience
// System.out.println("n:" + n + " max:" + max + " lowerbound:" + lower + " current:" + current);
// Base case
if (n <= 1 && lower == max) {
return 1;
}
// Recursive step
// Sequence complete, move to next column
if (current == max) {
// Make sure the lower bound does not go beyond the max. number
int updatedLower = (lower + 1 > max) ? lower : lower + 1;
return 1 + recursive(n - 1, max, updatedLower, updatedLower);
}
return 1 + recursive(n, max, lower, current + 1);
}
简而言之:
在第二个例子中:
n=2
最大值=3
{1,1}
{1,2}
{1,3}
{2,2}
{2,3}
{3,3}
注意由于从左到右的数字必须相等或更大的规则而出现的数字模式:
第二列:1>2>3>2>3>3
第一列:1>1>1>2>2>3
递归中的“下界”参数基本上是新“序列”可以采用的最低可能数字(其中每个序列为lower bound -> max number)。然后,基本情况是下限等于上限并且每列都完成了所有“序列”。可能不是一个非常清晰的解释 - 当您看到我复制粘贴的代码中的注释行打印出的内容时,它可能会有所帮助。
注意:也许可以用更少的参数进行递归。确保阅读大量有关递归的内容(例如wikipedia 或您的学习书?)。递归可以更轻松地找到解决方案并理解复杂和抽象的问题。