我在写一个递归函数来解决一个问题,在这个问题中,你需要找到所有的组合,以达到给定数字的目标和,并且每个数字都小于某个限制。
我写的代码如下:
results = []
def findSchedulesHelper(workHours_left, dayHoursLimit, days_left, res):
if workHours_left < 0:
return
elif workHours_left > 0 and days_left == 0:
return
elif workHours_left == 0 and days_left != 0:
for i in range(days_left):
res.append(0)
results.append(res)
return
elif days_left == 0 and workHours_left == 0:
results.append(res)
return
else:
for i in range(dayHoursLimit + 1):
res.append(i)
findSchedulesHelper(workHours_left - i, dayHoursLimit, days_left - 1, res)
res.pop()
def findSchedules(workHours, dayHours, pattern):
# Write your code here
num_question_mark = 0
total_hours_so_far = 0
for char in pattern:
if char == "?":
num_question_mark += 1
else:
total_hours_so_far += int(char)
hours_left_to_fill = workHours - total_hours_so_far
for i in range(dayHours + 1):
findSchedulesHelper(hours_left_to_fill - i, dayHours, num_question_mark - 1, [i])
print results
findSchedules(3,2,"??2??00")
但这给出了错误的答案。
如果我更改一行并使其成为:
results = []
def findSchedulesHelper(workHours_left, dayHoursLimit, days_left, res):
if workHours_left < 0:
return
elif workHours_left > 0 and days_left == 0:
return
elif workHours_left == 0 and days_left != 0:
for i in range(days_left):
res.append(0)
results.append(res)
return
elif days_left == 0 and workHours_left == 0:
results.append(res)
return
else:
for i in range(dayHoursLimit + 1):
findSchedulesHelper(workHours_left - i, dayHoursLimit, days_left - 1, res + [i])
def findSchedules(workHours, dayHours, pattern):
# Write your code here
num_question_mark = 0
total_hours_so_far = 0
for char in pattern:
if char == "?":
num_question_mark += 1
else:
total_hours_so_far += int(char)
hours_left_to_fill = workHours - total_hours_so_far
for i in range(dayHours + 1):
findSchedulesHelper(hours_left_to_fill - i, dayHours, num_question_mark - 1, [i])
print results
findSchedules(3,2,"??2??00")
那么一切都是正确的。我真的很困惑为什么会这样。我试着做了一些调试,发现append和pop并不像我期望的那样工作。如果有人能解释我做这个函数的两种方法之间到底有什么区别,那就太好了。