lintcode: Partition Equal Subset Sum

本文探讨了一个经典的计算机科学问题——如何判断一个只包含正整数的非空数组能否被划分为两个子集,使得这两个子集的元素之和相等。通过对示例的分析和提供一种动态规划解决方案,本文详细解释了实现这一目标的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];
        
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值