组合递归——回溯
我一直在尝试编码3个不同的递归功能(回溯)。第一个应显示所有排列(订单都不重要),并且有一个规格大小。第二个应显示所有循环排列。第三个应显示所有排列(订单很重要),并且有一个特定的大小。
我能够自己做第一个:
def Arranjo(list, repeat):
if repeat <= 0:
return [[]]
solution = []
for i in range(0, len(list)):
remainingList = list[:i] + list[i + 1 :]
for j in Arranjo(remainingList, repeat - 1):
solution.append([list[i]] + j)
return solution
# 0 to 100
list = [x for x in range(1, 101)]
print(Arranjo(list, 3))
我在其他两个练习中都面临一些问题。我已经花了几个小时尝试进行第二次练习,但是我对如何做不了解。那就是我能做的:
def PermutacaoCircular(list):
if len(list) == 0:
return
elif len(list) == 1:
return list
else:
solution = []
sub_solution = []
for i in range(len(list)):
// code here
return solution
list = [1, 2, 3]
print(PermutacaoCircular(list))
第三个,我什至不知道如何开始。
I've been trying to code 3 different recursive function(Backtracking). The first one should show all permutations(orders doesn't matters) and there's a specif size. The second one should show all cyclic permutations. The third one should show all permutations(orders matters) and there's a specif size.
I was able to do the first one by myself:
def Arranjo(list, repeat):
if repeat <= 0:
return [[]]
solution = []
for i in range(0, len(list)):
remainingList = list[:i] + list[i + 1 :]
for j in Arranjo(remainingList, repeat - 1):
solution.append([list[i]] + j)
return solution
# 0 to 100
list = [x for x in range(1, 101)]
print(Arranjo(list, 3))
I've been facing some issues in the other two exercises. I've already spent hours trying to do the second exercise, but I don't have any idea about how to do it. That's what I was able to do:
def PermutacaoCircular(list):
if len(list) == 0:
return
elif len(list) == 1:
return list
else:
solution = []
sub_solution = []
for i in range(len(list)):
// code here
return solution
list = [1, 2, 3]
print(PermutacaoCircular(list))
The third one, I don't even know how to start.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论