leetcode:416.分割等和子集(动态规划)

链接:https://leetcode-cn.com/problems/partition-equal-subset-sum/
实际上就是0-1背包问题, d p [ i ] [ j ] dp[i][j] dp[i][j]表示在 [ 0 , i ] [0,i] [0,i]中的元素是否能够组成和为j的子集
分取nums[i]与不去两种情况
d p [ i ] [ j ] = d p [ i − 1 ] [ j ] 或 d p [ i − 1 ] [ j − n u m s [ i ] ] dp[i][j] = dp[i-1][j]或dp[i-1][j-nums[i]] dp[i][j]=dp[i1][j]dp[i1][jnums[i]]
java代码:

class Solution {
     
    public boolean canPartition(int[] nums) {
     
        int sum = 0;
        for(int i:nums)
            sum+=i;
        if(sum%2==1)
            return false;
        int n = nums.length;
        boolean [] dp = new boolean [sum/2+1];
        dp[0]  =true;
        for(int i = 0;i<n;i++)
        {
     
            for(int j = sum/2;j>=0;j--)
            {
     
                if(j-nums[i]>=0&&dp[j-nums[i]]==true)
                    dp[j] = true;
            }
            if(dp[sum/2]==true)
                return true;
        }
        return false;
    }

你可能感兴趣的:(leetcode,leetcode,动态规划,算法,java)