思路:这个问题能够转化为求数组的一个子集,使得这个子集中的元素的和尽量接近sum/2,其中sum为数组中全部元素的和。这样转换以后这个问题就很相似0-1背包问题了:在n件物品中找到m件物品,他们的能够装入背包中,且总价值最大不过这里不考虑价值,就考虑使得这些元素的和尽可能接近sum/2。html
下面列状态方程:
dp[i][j]表示前i件物品中,总和最接近j的全部物品的总和,其中包括两种状况:数组
若是第i件物品没有包括在其中,则dp[i][j] = dp[i-1][j]
若是第i件物品包括在其中,则dp[i][j] = dp[i-1][j-vec[i]]post
固然,这里要确保j-vec[i] >= 0。学习
因此状态转移方程为: url
dp[i][j] = max(dp[i-1][j],dp[i-1][j-vec[i]]+vec[i]);spa
for (int i = 1; i <= len; ++i) { for (int j = 1; j <= sum / 2; ++j) { if(j>=vec[i-1]) dp[i][j] = max(dp[i-1][j],dp[i-1][j-vec[i-1]]+vec[i-1]); else dp[i][j] = dp[i - 1][j]; } }
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 给出一个长度为 2n 的整数数组,你的任务是将这些整数分红n组,每组两个一对,并求得 全部分组中较小的数 的总和(这个总和的值要尽量的大) Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4. Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000]. 思路:将整个数组升序排列,从下标为 0 处开始,每隔两个 取一个,并求和 class Solution(object): def arrayPartitionI(self, nums): return sum(sorted(nums)[::2])