描述
n = range of elements
k = population of each cell
s = solution so far
if the remaining population is 0
print the solution
else
if there are still elements available, search two cases:
(1) Don't use **n** in the solution; recur.
(2) Do use **n** in the solution;
decrease the population by 1 and recur.
调试
调试器非常适合查找逻辑流问题。对于全局,您有时需要收集更多数据以进行整体调查。坚持几个打印语句来跟踪逻辑,让它向你喷出几行输出。
对于函数,我建议第一个语句是打印以显示“ENTER”、函数名称(在这种情况下是冗余的)和参数。同时在决策点打印:跟踪递归步骤。
跟踪此例程
这是我跟踪问题时的输出,每个递归级别缩进 2 个空格:
ENTER 4 3
RECUR without n
ENTER 3 3
RECUR without n
ENTER 2 3
RECUR without n
ENTER 1 3
RECUR without n
ENTER 0 3
RECUR using n
ENTER 0 2 1
RECUR using n
ENTER 1 2 2
RECUR without n
ENTER 0 2 2
RECUR using n
ENTER 0 1 12
RECUR using n
ENTER 2 2 3
RECUR without n
ENTER 1 2 3
RECUR without n
ENTER 0 2 3
RECUR using n
ENTER 0 1 13
RECUR using n
ENTER 1 1 23
RECUR without n
ENTER 0 1 23
RECUR using n
ENTER 0 0 123
123
RECUR using n
ENTER 3 2 4
RECUR without n
ENTER 2 2 4
RECUR without n
ENTER 1 2 4
RECUR without n
ENTER 0 2 4
RECUR using n
ENTER 0 1 14
RECUR using n
ENTER 1 1 24
RECUR without n
ENTER 0 1 24
RECUR using n
ENTER 0 0 124
124
RECUR using n
ENTER 2 1 34
RECUR without n
ENTER 1 1 34
RECUR without n
ENTER 0 1 34
RECUR using n
ENTER 0 0 134
134
RECUR using n
ENTER 1 0 234
234