[LeetCode] Partition Equal Subset Sum划分数组形成两个和相等的子集

声明:原题目转载自LeetCode,解答部分为原创

Problem :

        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.

Solution:

        思路:动态规划类型的题目。给定数组array[n],假定函数f(a)代表数值中和为a的子集的个数,则状态转换方程为:

f(a) = f(a) + f(a - array[ i ]),其中 i 的数值为 0,1,2,3.......n 

初始化f(0) = 1,f(else)= 0。穷举所有的情况,注意在每个子集的和的计算中,一个元素只能出现一次。

当整个数组的和为奇数时,返回0,和为偶数时,返回f(sum_of_array / 2)。

        代码如下:

#include
#include
using namespace std;

class Solution {
public:
    bool canPartition(vector& nums) {
        int sum = 0;
        for(int i = 0 ; i < nums.size() ; i ++)
        {
        	sum += nums[i];
		}
		
		if(sum % 2 != 0)
			return 0;
			
		int target = sum / 2;
		
		vector count_of_sum(sum + 1, 0);
		count_of_sum[0] = 1;
		
		for(int i = 0 ; i < nums.size(); i ++)
		{
			int add = nums[i];
			for(int j = sum; j >= add; j --)
			{
				count_of_sum[j] += count_of_sum[j - add];
			}
		}
		return count_of_sum[target];
    }
};

int main()
{
	vector temp(8,0);
	for(int i = 0; i < 8; i ++)
	{
		temp[i] = i;
	}
	Solution text;
	cout << text.canPartition(temp) << endl;
	return 0;
}


你可能感兴趣的:(LeetCode)