LeetCode No.416 Partition Equal Subset Sum

来源:互联网 发布:淘宝黑搜任务怎么做 编辑:程序博客网 时间:2024/05/18 14:24

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: trueExplanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]Output: falseExplanation: The array cannot be partitioned into equal sum subsets.
====================================================================================
题目链接:https://leetcode.com/problems/partition-equal-subset-sum/
题目大意:给定一个数组,求该数组能不能分成和相等的两部分。
思路:用动态规划(DP)求解。
1、先计算数组所有元素之和sum,当和为奇数时肯定不能分成两个和相等的部分
2、half = sum / 2 ,新建一个二维bool数组dp[n][half+1],其中dp[i][j]表示前i个数是否能构成j。
3、初始化dp数组,dp[0][0] = true ,如果nums[0] <= half ,则dp[0][nums[0]] = true
4、dp[i][j] = dp[i][j] || dp[i-1][j-nums[i]] 
参考代码:
class Solution {public:    bool canPartition(vector<int>& nums) {        int n = nums.size() , sum = 0 , maxer = 0 ;        for ( int i = 0 ; i < n ; i ++ )            sum += nums[i] ;        int half = sum >> 1 ;        if ( n < 2 || sum % 2 )            return false ;        vector < vector <bool> > dp ( n , vector <bool> ( half + 1 , false ) ) ;        dp[0][0] = true ;        if ( nums[0] <= half )            dp[0][nums[0]] = true ;        for ( int i = 1 ; i < n ; i ++ )        {            for ( int j = 0 ; j <= half ; j ++ )            {                dp[i][j] = dp[i][j] || dp[i-1][j] ;                if ( j >= nums[i] )                    dp[i][j] = dp[i][j] || dp[i-1][j-nums[i]] ;                if ( dp[i][half] )                    return true ;            }        }        return false ;    }};


0 0