Throw the question:
All solutions of a given array equal to a fixed value, such as the list L = [1, 2, 3, 4, 5], for any combination of the results of 10 of all the answers
Problem Analysis:
It is actually all permutations of the list, and then the values of each permutation are calculated, and the combined result is equal to the evaluated value.
The code implementation is the first generation and L equal length of the full 0 list, 0 means that the list of the number of positions is not taken, 1 means the list of the number of places to take, so always recursive, until the full 1
#-*-coding:utf-8-*-#Date: 2018/6/11#Author: Small mouse#all solutions of a given array equal to a fixed valuelist = [1, 2, 3, 4, 5]val= 10#generate a full 0 list of equal lengthsx = [0 forIinchRange (0,len (list))]#Recursive method x record list is not taken, I represents the current recursive position, has represents the current value of all anddefGet_val (x,i,has):ifi > Len (x)-1: return ifHas + list[i] = =Val:#match a condition recordX[i] = 1Print(x) x[i]=0#The current position takes execution onceX[i] = 1Get_val (X,i+1,has+List[i])#current position does not take execution onceX[i] =0 get_val (x, I+ 1, has) Get_val (x,0,0)#=========== Results =========#[1, 1, 1, 1, 0] "[1,2,3,4] 1+2+3+4=10#[1, 0, 0, 1, 1] "[1,4,5] 1+4+5=10#[0, 1, 1, 0, 1] "[2,3,5] 2+3+5=10
Python any combination of the given array equals a fixed value of all solutions