[WXM] LeetCode 416. Partition Equal Subset Sum C++

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.

Approach

  1. 题目大意问你该数组能否分成两组,两组和相等。虽然这是动态规划类题,但看着数据量不大,就想着用深搜解决,发现超时,最后看了大神播客,这道题也是要用递推的方式,一开始我也想着用递推的方式解决,可是我还不会变形,只会处理数组中的数使用次数不限这类题,然后仔细研究了下,发现可以反过来用,就可以达到题目的要求,我们首先枚举数组,然后再枚举0~平均数,以前来说是先枚举0~平均数,再枚举数组,但是就会导致数组过度使用,然后我们标记dp[平均数]=1,然后if(dp[i])dp[i-nums[i]]=1,这段代码其实是浓缩了搜索的过程,只有dp[i]可达,dp[i-nums[i]]=1才可达。
  2. [WXM] LeetCode 377. Combination Sum IV C++
  3. [WXM] LeetCode 279. Perfect Squares C++
  4. 以上的题也是用到递推的方法。

Code

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        if (nums.size() < 2)return false;
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if (sum % 2 != 0)return false;
        int c = sum / 2;
        vector<int>dp(c + 1, 0);
        dp[c] = 1;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i++) {//枚举数组,确保只用一次
            for (int j = 0; j<=c; j++) {//从零开始枚举,也是为了确保只用一次
                if (nums[i] > j)continue;
                if (dp[j])dp[j - nums[i]] = 1;
                if (dp[0])return true;
            }
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/WX_ming/article/details/82077868