简体   繁体   English

带条件的Python排列(回溯)

[英]Python permutations with condition (backtracking)

I want to solve a problem using backtracking. 我想使用回溯解决问题。 As in... I'm given a list of numbers and I want to find all the possible permutations that respect a given condition, using backtracking. 就像在...中,我得到了一个数字列表,我想使用回溯找到尊重给定条件的所有可能排列。

I have the code for generating a list of permutations but it's not helping cause I can't check each permutation individually before adding it to the list so it's not backtracking, it's just recursive. 我有用于生成排列列表的代码,但它无济于事,因为我无法在将每个排列添加到列表之前单独检查每个排列,因此它不会回溯,只是递归的。 I also understand the way backtracking works for: permutations from 0 to x but not for a list... 我也了解回溯的工作方式:从0到x的排列,但不是列表的排列...

This is my permutation list generator 这是我的排列列表生成器

def permutare(self, lista):
        if len(lista) == 1:
            return [lista]
        res = []
        for permutation in self.permutare(lista[1:]):
            for i in range(len(lista)):
                res.append(permutation[:i] + lista[0:1] + permutation[i:])
        return res

Works but not helping me. 有效,但无济于事。 I tried inserting the validation somewhere in there but nowhere works.. I tried all the permutation algorithms I could find. 我尝试将验证插入到某处,但无处工作。.我尝试了所有可以找到的置换算法。 I need one with backtracking 我需要一个回溯

Any idea/algorithm/pseudocode for backtracking permutations with conditions? 对条件回溯排列有任何想法/算法/伪代码吗?

Here's a solution that uses backtracking by swapping elements in the list. 这是一个通过交换列表中的元素来使用回溯的解决方案。

The basic idea is: 基本思想是:

  • Swap each element into the start position. 将每个元素交换到开始位置。
  • Compute the remaining partitions with indices [0:start] fixed 计算索引为[0:start]的其余分区

Code: 码:

def swap(lista, idx1, idx2):
    temp = lista[idx1]
    lista[idx1] = lista[idx2]
    lista[idx2] = temp

def valid():
    return True

def permutare(lista, start):
    if start >= len(lista):
        if valid():
            return [list(lista)]

    output = []
    for idx in xrange(start, len(lista)):
        swap(lista, start, idx)
        output.extend(permutare(lista, start + 1))
        swap(lista, start, idx)  # backtrack
    return output

print len(permutare(['a','b','c'], 0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM