This problem has been implemented with Python, want to rewrite into PHP code, stuck on the element is not repeated on the combination, to give a thought ~
That is, there are n elements, maybe A
+ B
equals 100, but the maximum combination that satisfies the result does not exceed 120
, just A
+ C
+ D
equals 191.
# -*- coding=UTF-8 -*-import itertoolsloop = [509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644]m = 0m_list = []for i in range(0, len(loop)): # 目的是打乱其排序,找出任意种可能 rets = list(itertools.combinations(loop, i)) for ret in rets: # 将循环器中的元组求和 s = sum(ret) if s <= 5000 and s > m: # 求和值 m = s # 组合的列表 m_list = ret# 最大值print(m)# 求和的元素print(m_list)
Reply content:
This problem has been implemented with Python, want to rewrite into PHP code, stuck on the element is not repeated on the combination, to give a thought ~
That is, there are n elements, maybe A
+ B
equals 100, but the maximum combination that satisfies the result does not exceed 120
, just A
+ C
+ D
equals 191.
# -*- coding=UTF-8 -*-import itertoolsloop = [509, 838, 924, 650, 604, 793, 564, 651, 697, 649, 747, 787, 701, 605, 644]m = 0m_list = []for i in range(0, len(loop)): # 目的是打乱其排序,找出任意种可能 rets = list(itertools.combinations(loop, i)) for ret in rets: # 将循环器中的元组求和 s = sum(ret) if s <= 5000 and s > m: # 求和值 m = s # 组合的列表 m_list = ret# 最大值print(m)# 求和的元素print(m_list)
You're going to test the algorithm, right?
rets = list(itertools.combinations(loop, i))
Direct such a poor lift is certainly not suitable ah, a large amount of data will inevitably hang, this should be considered a knapsack problem, the specific description can be seen
Knapsack problem (knapsack problem) is a NP-complete problem of combinatorial optimization. The problem can be described as: given a set of items, each item has its own weight and price, within a limited total weight, we choose how to make the total price of the item the highest. The name of the problem comes from how to choose the most suitable item to be placed in a given backpack.
Https://zh.wikipedia.org/wiki ...
If you want PHP in the Itertools function can see this
https://github.com/alts/iter.php