关键词:动态规划, 滚动数组, 将数组划分成和相等的两部分
题目描述:
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
- Each of the array element will not exceed 100.
- The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
即将给定的数组划分成两部分, 这两部分数组和相等。
题目解析:
使用动态规划的方法, 记二维布尔数组 A[i, j] 表示使用数组的前 i 个数字, 是否能构成和为 j 的数组状态转移方程为:
A[0,0] = 1
A[i+1,j] = A[i,j] or A[i, j - nums[i]]
初始化时, A[0, 0] = 1, 表示不使用任何数字时, 能构成和为0的数组(空数组)。
当计算A[i+1, j]时,若使用前i个数字不使用第i个数字能构成和j, 那么A[i+1,j] = true; 若使用前i个数字且使用第i个数字时,若A[i, j - nums[i]] 为true, 则A[i+1, j] = true.
参考代码:
class Solution {
public:
bool canPartition(vector<int>& nums) {
int su = 0;
for (int i : nums)su += i;
if (su & 1)return false;
int half = su / 2;
vector<vector<bool> > dp(nums.size()+1, vector<bool>(half + 1, false));
/*
A[0,0] = 1
A[i+1,j] = A[i,j] or A[i, j - nums[i]]
*/
dp[0][0] = true;
for (int i = 0;i < nums.size();++i){
for (int j = 0;j <= half;++j){
dp[i+1][j] = dp[i][j];
if (j >= nums[i] && dp[i][j - nums[i]])dp[i+1][j] = true;
}
}
return dp[nums.size()][half];
}
};
上述算法的时间复杂度为O(nums.size() * half), 空间复杂度为(O((nums.size() + 1)* (half + 1) )), 其中half为所有数字总和的一半。
使用滚动数组可以降低空间的使用量, 原因是动态规划的过程中, 存在不再使用的旧值,可以用新值将旧值覆盖。
状态转移方程为:
B[0] = 1
B'[j] = B[j] or B[j - nums[i]]
需要注意, 不要将同一个位置的数字相加多遍, 若j 从低往高数, 会将同一数字相加多遍。若j 从高往低数, 则可以保证同一个数字最多只被加一遍。
参考代码:
class Solution {
public:
bool canPartition(vector<int>& nums) {
int su = 0;
for (int i : nums)su += i;
if (su & 1)return false;
int half = su / 2;
vector<bool> dp(half + 1, false);
dp[0] = true;
for (int k : nums){
for (int j = half; j >= k;--j){
if (!dp[j] && dp[j - k])dp[j] = true;
}
}
return dp[half];
}
};
时间复杂度为O(nums.size() * half), 空间复杂度为O(half ), 可见使用滚动数组, 时间复杂度不变,但空间复杂度减少了很多。