Partition Equal Subset Sum

本次題目也是關於動態規劃的練習,Partition Equal Subset Sum,題目要求如下:

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:

  1. Each of the array element will not exceed 100.
  2. 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.
大致要求為查看一個給定的數列能不能劃分成兩個相等的子數列,首先為動態規劃創建一個布爾數組result查看在result內的下標是否可達,顯然大小為sum/2,所以我們要返回result[sum/2]的值,如果sum/2不為整數,則這個子數列便沒有相等的兩個子數列,返回false。

透過遍歷整個數列,如果我們可以找到有數相加到sum/2,則返回true,因為剩餘的數也可以相加到sum/2。

根據動態規劃,如果數字i可以由前面的數相加可達,則i + num也是可達的。

bool canPartition(vector<int>& nums)
{
int sum = accumulate(nums.begin(), nums.end(), 0);
int temp, half = sum / 2;
if(sum % 2 != 0) return false;
vector<bool> result(half + 1, false);
result[0] = true;

for(int i = 0; i < nums.size(); i++)
{
temp = nums[i];
for(int j = half; j >= temp; j--)
{
if (result[i - temp] == true)
                result[i] = true;
}
}
return result[half];
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章