和为某个特定值的数组元素组合(是否存在/个数/所有组合)

1. 数组中是否存在某个元素组合,使得组合中所有元素的和为某个特定值
public static boolean findSum(int[] nums, int s) {
    // dp[i][j] whether we can get j after scanning the first i elements
    boolean[][] dp = new boolean[nums.length + 1][s + 1];
    dp[0][0] = true;
    for (int i = 1; i <= nums.length; i++) {
        for (int j = 0; j <= s; j++) {
            dp[i][j] = dp[i-1][j];
            if (!dp[i][j] & j >= nums[i-1]) {
                dp[i][j] = dp[i-1][j-nums[i-1]];
            }
        }
    }

    return dp[nums.length][s];
}
2. 数组中和为某个特定值的元素组合个数
public static int getSum(int[] nums, int s) {
    // dp[i][j] means the number of ways of getting j after scanning the first i elements
    int[][] dp = new int[nums.length + 1][s + 1];
    dp[0][0] = 1;
    for (int i = 1; i <= nums.length; i++) {
        for (int j = 0; j <= s; j++) {
            dp[i][j] = dp[i-1][j];
            if (j >= nums[i-1]) {
                dp[i][j] += dp[i-1][j-nums[i-1]];
            }
        }
    }

    return dp[nums.length][s];
}
3. 数组中和为某个特定值的所有元素组合(回溯法)
public static List<List<Integer>> getAllSum(int[] nums, int s) {
    List<List<Integer>> res = new ArrayList<>();
    backtrack(res, new ArrayList<>(), nums, s, 0, 0);

    return res;
}


public static void backtrack(List<List<Integer>> res, List<Integer> temp, int[] nums, int s, int cusSum, int start) {
    if(curSum == s) {
        res.add(new ArrayList<>(temp));
    }
    for (int i = start; i < nums.length; i++) {
        temp.add(nums[i]);
        backtrack(res, temp, nums, s, curSum + nums[i], i + 1);
        temp.remove(temp.size() - 1);
    }
}
测试
public static void main(String[] args) {
	int[] nums = {0, 2, 2, 4};
    System.out.println(findSum(nums, 4));
    System.out.println(getSum(nums, 4));
    System.out.println(getAllSum(nums, 4));
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值