lintcode: Partition Equal Subset Sum

504 篇文章 0 订阅
66 篇文章 0 订阅

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.

 Notice

Each of the array element will not exceed 100.
The array size will not exceed 200.

Example

Given nums = [1, 5, 11, 5], return true
two subsets: [1, 5, 5], [11]

Given nums = [1, 2, 3, 9], return false

class Solution {
public:
    /**
     * @param nums a non-empty array only positive integers
     * @return return true if can partition or false
     */
    bool canPartition(vector<int>& nums) {
            // Write your code here
            
    	int sum = 0;
    	for (int i = 0; i< nums.size(); i++)
    		sum += nums[i];
    
    	if (sum % 2)
    		return false;
    
    	int target = sum / 2;
    
    	vector<vector<bool>> dp(nums.size() + 1, vector<bool>(target + 1));
    
    	for (int i = 0; i <= nums.size(); i++)
    	{
    		for (int j = 0; j <= target; j++)
    		{
    			dp[i][j] = false;
    		}
    	}
    
    	for (int i = 0; i <= nums.size(); i++)
    		dp[i][0] = true;
    
    
    	for (int i = 1; i <= nums.size(); i++)
    	{
    		for (int k = 1; k <= target; k++)
    		{
    			if (dp[i - 1][k] == true)
    			{
    				dp[i][k] = true;
    			}
    
    			if (k - nums[i - 1] >= 0 && dp[i - 1][k - nums[i - 1]] == true)
    			{
    				dp[i][k] = true;
    			}
    		}
    	}
    
    	return dp[nums.size()][target];
        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值