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

    分析

    这道题用动态规划,dp[i] 表示是否能从数组中取得数字之和为i , 动态转移方程dp[i]=dp[i]||dp[i-n] .

    class Solution {
    public:
        bool canPartition(vector<int>& nums) {
             int s=accumulate(nums.begin(),nums.end(),0);
             if(s%2!=0) return false;
             vector<int> dp(s/2+1,0);
             dp[0]=1;
             vector<int> visited(s/2+1,0);
             for(auto o:nums)
                 for(int i=s/2;i>=o;i--)
                     dp[i]=dp[i-o]||dp[i];
             return dp[s/2]==1;
        }
    };
    
  • 相关阅读:
    LDAP+Jenkins
    LDAP+SASL+SVN
    Ubuntu下的LDAP服务搭建
    LDAP+Confluence
    LDAP+Nextcloud
    vim -d
    linux默认编辑器
    vim相关调优
    MySQL中的保留字
    RHEL7配置ip地址
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10066934.html
Copyright © 2011-2022 走看看