LeetCode 416 The Road to LeetCode of HEROIDNG

Given a non-empty array containing only positive integers. Is it possible to divide this array into two subsets so that the sum of the elements of the two subsets is equal.

note:

每个数组中的元素不会超过 100
数组的大小不会超过 200

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be divided into [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: An array cannot be divided into two elements and equal subsets.

Problem-solving idea:
If you can understand this problem as a dynamic programming problem, it will be solved very well. First, if it is an array of 0 or 1, it will definitely not work. If the sum of the array is odd, it will not work. If the largest item in the array is greater than the sum Half, it doesn’t work. At this time, you can do 0,1 knapsack in the rest of the situation. dp[i][j] represents from 0 to i, and whether the sum is j can be established, so there are only two values ​​of true and false. The code is as follows :

class Solution {
    
    
public:
    bool canPartition(vector<int>& nums) {
    
    
        // 如果nums只有一个数
        int n = nums.size();
        if (n < 2) {
    
    
            return false;
        }
        // 获取总值
        int sum = accumulate(nums.begin(), nums.end(), 0);
        // 获取最大值
        int maxNum = *max_element(nums.begin(), nums.end());
        // 如果是0或1
        if (sum & 1) {
    
    
            return false;
        }
        // 如果最大的那个数大于和的一半
        int target = sum / 2;
        if (maxNum > target) {
    
    
            return false;
        }
        // 创建dp
        vector<vector<int>> dp(n, vector<int>(target + 1, 0));
        for (int i = 0; i < n; i++) {
    
    
            dp[i][0] = true;
        }
        dp[0][nums[0]] = true;
        for (int i = 1; i < n; i++) {
    
    
            int num = nums[i];
            for (int j = 1; j <= target; j++) {
    
    
                if (j >= num) {
    
    
                    dp[i][j] = dp[i - 1][j] | dp[i - 1][j - num];
                } else {
    
    
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[n - 1][target];
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/109007532