鱼C论坛

 找回密码
 立即注册
查看: 398|回复: 1

回溯算法尝试

[复制链接]
发表于 2020-4-11 21:50:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在leetcode上面看到跳楼梯的问题,自已想尝试用回溯算法将所有可能的情况全部呈现出来,代码如下(死循环):
  1. def test():
  2.    
  3.     ans = []
  4.     index = 0

  5.     def go(index, step):
  6.         index += step
  7.         return index
  8.    
  9.     def back(index, step):
  10.         index -= step
  11.         return index
  12.    
  13.     def add_solution(res):
  14.         ans.append(res)
  15.         return ans
  16.    
  17.     def main(list_ = [2,3,1,4], res = []):
  18.         print(index)
  19.         for step in range(1, list_[index] + 1):
  20.             if index < len(list_) - 1:
  21.                 res.append(step)
  22.                 go(index, step)
  23.                 print(index, res)
  24.                 test(list_, res)
  25.             elif index == len(list_) - 1:
  26.                 add_solution(res)
  27.                 back(index, step)
  28.                 print(index)
  29.                 break
  30.             elif index > len(list_) - 1:
  31.                 break
  32.         res = res[:-1]
  33.         print(res, ans)
  34.             
  35.     main()
复制代码

其中list_的index为楼梯的层数,list_[index]为当前楼梯可行进的最大步数,希望输出ans为所有爬楼的可能走法;
在main中会出现死循环,原因是go和back函数并没有想我想象中的修改index的值,希望大佬能教教我这里是什么原理;
如果能教教我回溯算法就更好了啊哈哈哈
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-11 22:07:02 | 显示全部楼层
try this:
  1. def test():
  2.    
  3.     ans = []
  4.     index = 0

  5.     def go(index, step):
  6.         nonlocal index
  7.         index += step
  8.    
  9.     def back(index, step):
  10.         nonlocal index
  11.         index -= step
  12.    
  13.     def add_solution(res):
  14.         ans.append(res)
  15.         return ans
  16.    
  17.     def main(list_ = [2,3,1,4], res = []):
  18.         print(index)
  19.         for step in range(1, list_[index] + 1):
  20.             if index < len(list_) - 1:
  21.                 res.append(step)
  22.                 go(step)
  23.                 print(index, res)
  24.                 test(list_, res)
  25.             elif index == len(list_) - 1:
  26.                 add_solution(res)
  27.                 back(step)
  28.                 print(index)
  29.                 break
  30.             elif index > len(list_) - 1:
  31.                 break
  32.         res = res[:-1]
  33.         print(res, ans)
  34.             
  35.     main()
复制代码
这个是变量作用域和不可变对象的问题。

PS:建议楼主先打好基础,再去力扣做题哦
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-14 17:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表