组合递归——回溯

发布于 2025-01-19 03:30:23 字数 915 浏览 1 评论 0原文

我一直在尝试编码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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文