简体   繁体   中英

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...

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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