动态规划学习:分割数组

一、分割数组

  • 给定一个只包含正整数的非空数组nums。请你判断是否可以将这两个数组分割成两个子集,
    使得两个子集的元素和相等

二、思路分析

  • 可以转化为01背包问题,只不过不是求最大价值,而是求有没有可能装满背包,
    只需要把所有情况列举出来就好

三、代码实现

1、使用二维数组

    public static boolean splitarray(int[] nums){
        int n = nums.length;
        int sum = 0;
        for (int i = 0; i < n; i++){
            sum += nums[i];
        }

        if (sum % 2 != 0) return false; //若为偶数,肯定不能等分
        int target = sum / 2;

        boolean dp[][] = new boolean[n][target + 1];
        //dp[i][j]表示前i个数能否凑够j值

        dp[0][0] = true;
        if (nums[0] < target){
            dp[0][nums[0]] = true;
        }

        for (int i = 1; i < n; i++){
            for (int j = 0; j <= target; j++){
                if (j - nums[i] >= 0){
                    //放或者不放有一个为true就行
                    dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i]];
                } else {
                    //选择不放,上一个为true就为true
                    dp[i][j] = dp[i-1][j];
                }
            }
        }

        return dp[n-1][target];
    }

2、使用一维数组

package OneDaySuanFa;

public class SplitArray {

    //转为一维数组
    public static boolean splitarray1(int[] nums){
        int n = nums.length;
        int sum = 0;
        for (int i = 0; i < n; i++){
            sum += nums[i];
        }

        if (sum % 2 != 0) return false;
        int target = sum / 2;

        boolean[] dp = new boolean[target+1]; //dp[i]表示是否能够凑够i,如果可以,返回true;如果不可以,返回false

        dp[0] = true;
        if (nums[0] < target) dp[nums[0]] = true;

        for (int i = 1; i < n; i++){
            for (int j = target; j >= 0; j--){
                if (j >= nums[i]){
                    dp[j] = dp[j] || dp[j-nums[i]];
                }
            }
        }

        return dp[target];
    }

    public static void main(String[] args) {
        int[] n1 = new int[]{1,11,5,5};
        System.out.println(splitarray1(n1));
        int[] n2 = new int[]{2,2,2,4};
        System.out.println(splitarray1(n2));
        int[] n3 = new int[]{1,3,5};
        System.out.println(splitarray1(n3));
        int[] n4 = new int[]{1,1,10,4,12};
        System.out.println(splitarray1(n4));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱夜来香A

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值