【LeetCode 416】 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:

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.

思路

记忆化搜索超时了。
递归,想了很久。考虑到数据范围和数组长度,target 在 10^4 范围。每次新增加一个数字时,从之前所有能组成的数字里,给当前能新组成的数字标记。

代码

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

好烦啊。。。。今天。。。
这是一道去年做过的题了。。貌似。。懒得更新了。

发布了243 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104462431