zoukankan      html  css  js  c++  java
  • 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:

    1. Each of the array element will not exceed 100.
    2. 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: DP. [C++]

    class Solution {
    public:
        bool canPartition(vector<int>& nums) {
            int sum = std::accumulate(nums.begin(), nums.end(), 0);
            if (sum % 2 != 0) return false;
            vector<int> dp(sum+1, 0);
            dp[0] = 1;
            for (int num : nums) {
                for (int i = sum; i >= 0; --i) 
                    if (dp[i]) dp[i+num] = 1;
                if (dp[sum/2]) return true;
            }
            return false;
        }
    };
    

      

    Analysis:

    dp[i][j] : whether we can sum to j using first i numbers.

    dp[i][j] = true if dp[i-1][j-num]

    check dp[n-1][sum/2]

    init dp[-1][0] = true

    Time complexity: O(n^2*sum) -> O(n*sum)

    Space complexity: O(sum)

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    二叉树
    tomcat和jvm调优
    服务器正向代理
    LRU算法
    《转载》TCP三次握手中SYN,ACK,Seq三者的关系
    python的字符串、集合、for循环、异常等基础语法
    configparser_配置解析器
    hashlib模块
    悟_面向对象_小游戏和进阶
    面向对象_new,__eq__,__hash__
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10404051.html
Copyright © 2011-2022 走看看