标签:style blog http color os io strong for ar
"Look Stephen, here‘s a list of the items that need to be loaded onto the ship. We‘re going to need a lot of batteries." Nikola handed him a notepad.
"What are the numbers next to the items?"
"That is the weight of each item."
"Er, why?"
"So you can see how much your trading cards and comic book collection will weigh us down during flight." Rang Sofias voice from the phone tube.
"What is she talking about?” asked Nikola “Ooooh, nevermind, that was sarcasm. It’s important because your load-stabilizing belt is broken and there is no way that we can find a new one right now. That’s why, when you carry the things on the list, you’ll have to redistribute their weights in order to get the minimal weight in each arm."
"Okay, so I have to figure out how many batteries I should hold in each hand to prevent them from breaking when they inevitably fall to the ground. Got it."
You have been given a list of integer weights. You should help Stephen distribute these weights into two sets, such that the difference between the total weight of each set is as low as possible.
Input data: A list of the weights as a list of integers.
Output data: The number representing the lowest possible weight difference as a positive integer.
原题链接: http://www.checkio.org/mission/loading-cargo/
题目大义: 将数组中的数分为两组, 使得两组和之差最小
思路: 暴力法, 计算出所有分组和, 求最小差值; 时间复杂度N^2
1 def checkio(data): 2 #cal all possible subset sum 3 minmum_gap = 100 4 sub_sum = {0} 5 total_sum = sum(data) 6 7 for each in data: 8 tmp_list = [] 9 10 for pre in sub_sum: 11 tmp_sum = each + pre 12 13 if tmp_sum not in sub_sum: 14 tmp_list.append(tmp_sum) 15 16 tmp_gap = abs((tmp_sum << 1) - total_sum) 17 18 if tmp_gap < minmum_gap: 19 minmum_gap = tmp_gap 20 21 for new_sum in tmp_list: 22 sub_sum.add(new_sum) 23 24 #replace this for solution 25 return minmum_gap
标签:style blog http color os io strong for ar
原文地址:http://www.cnblogs.com/hzhesi/p/3935428.html