给定和的子集计数

7fhtutme  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(300)

我正在尝试解决给定和leetcode问题的子集计数问题,我的代码在大多数测试用例中运行良好,但它不处理数组中出现“0”的情况。
如: arr[] :{0,0,0,0,1,0,0,0,0} , sum: 1 这里的输出应该是 256 .
这是我的代码:

private int[][] dp;

/**nums => input array
    n => nums.length-1
    sum => target sum

**/

public int findNoOfSubset(int[] nums, int n, int sum) {
    //System.out.println(n  +" " + sum);
    if(sum == 0){
        return 1;
    }

    if(n < 0 || sum < 0) {
        return 0;
    }

    if(dp[n][sum] != -1) {
        return dp[n][sum];
    }

    if(sum >= nums[n]) {
        return dp[n][sum] = findNoOfSubset(nums, n-1, sum-nums[n]) + findNoOfSubset(nums, n-1, sum);
    }

    return dp[n][sum] = findNoOfSubset(nums, n-1, sum);
}

有人能指导我如何处理0元素的情况吗。

fquxozlt

fquxozlt1#

另一种看待这个问题的方法是找到子集和的数量。

// Create a map with key as the sum of a subset and value as the number of ways this sum was found.
Map<Integer, Integer> m = new HashMap<>(); 
// initialising as 0 can be found by selecting no numbers 
primary.put(0,0);
for (Integer i : numbers) {
  List<Integer> newSums = new ArrayList<>();
  for (Integer possibleSum : m.keySet()) {
        if (i+possibleSum > targetSum)
          continue;
        newSums.add(i+possibleSum);
  }
  for (Integer newPossibleSum : newSums) {
        m.put(newPossibleSum, m.getOrDefault(newPossibleSum, 0)+1);
  } 
}
return m.getOrDefault(targetSum,0);
ecbunoof

ecbunoof2#

我发现了我的错误,只是张贴了解决方案,以防有人面临同样的问题。

public int findNoOfSubset(int[] nums, int n, int sum) {
    if(sum == 0 && n<0){
        return 1;
    }

    if(n < 0 || sum < 0) {
        return 0;
    }

    if(dp[n][sum] != -1) {
        return dp[n][sum];
    }

    if(sum >= nums[n]) {
        return dp[n][sum] = findNoOfSubset(nums, n-1, sum-nums[n]) + findNoOfSubset(nums, n-1, sum);
    }

    return dp[n][sum] = findNoOfSubset(nums, n-1, sum);
}

相关问题