给定 nums =[3, 2, 3, 1, 5], target = 13
因为 nums[0] + nums[1] +nums[2] + nums[4]= 3+2+3+5=13 所以返回 [0, 1, 2, 4]
from itertools import combinations a = [3, 2, 3, 1, 5] target = 13 # 为数组标记下标 def markingIndex(a): arr = [] for key, value in enumerate(a): obj = {"index": key, "value": value} arr.append(obj) return arr bb = markingIndex(a) # 为数组做了排列组合 arr1 = [] for i in range(1, len(bb)): if i + 1 > len(a): break else: arr1 += list(combinations(bb, i + 1)) # 对排列组合的数据求和,与目标值去做对比,当相等的时候,结束对比,最终返回下标 ee = [] for cc in arr1: print(cc) sumData = 0 for dd in cc: sumData += dd["value"] if sumData == target: for e in cc: ee.append(e["index"]) break print(ee)