In this Leetcode Partition Equal Subset Sum problem solution we have given non-empty array nums 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.

Leetcode Partition Equal Subset Sum problem solution


Problem solution in Python.

class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        if sum(nums)%2!=0:
            return False
        var=sum(nums)//2
        dp=[[0]*(var+1) for i in range(len(nums))]
        for i in range(len(nums)):
            dp[i][0]=1
        for i in range(var+1):
            if i==nums[0]:
                dp[0][i]=1
                break
        for i in range(1,len(nums)):
            for  j in range(1,var+1):
                if nums[i]<=j:
                    dp[i][j]=dp[i-1][j]+dp[i-1][j-nums[i]]
                else:
                    dp[i][j]=dp[i-1][j]
                    
                    
        return True if dp[len(nums)-1][var] else False



Problem solution in Java.

public class Solution {
    public boolean canPartition(int[] nums) {
        if (nums == null || nums.length < 1) {
            return true;
        }
        int sum = 0;
        for (int i : nums) {
            sum += i;
        }
        if (sum % 2 == 1) {
            return false;
        }
        sum /= 2;
        return isSumSubarray(nums, sum, nums.length - 1);
    }
    
    private boolean isSumSubarray(int[] nums, int sum, int last) {
        if (sum == 0) {
            return true;
        }
        if (sum < 0 || last < 0) {
            return false;
        }
        return (isSumSubarray(nums, sum, last - 1) || 
            isSumSubarray(nums, sum - nums[last], last - 1));
    }
}


Problem solution in C++.

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


Problem solution in C.

bool canPartition(int* nums, int numsSize) {
    int s=0;
    for(int i=0;i<numsSize;i++)
        s+=nums[i];
    if(s%2)
        return false;
    s=s/2;
    int* dp=malloc(sizeof(int)*(s+1));
    if(nums[0]<=s)
        dp[nums[0]]=1;
    for(int i=1;i<numsSize;i++){
        for(int j=0;j<=s;j++){
            if(dp[j]==1&&j+nums[i]<=s)
                dp[j+nums[i]]=1;
        }
        if(nums[i]<=s)
            dp[nums[i]]=1;
    }
    return dp[s];
}