The sum of the number of combinations 2

topic:

Given an array of candidates and a target number target, find out all combinations of candidates that can make the sum of numbers target.
Each number in candidates can only be used once in each combination.

Description:

All numbers (including the target number) are positive integers.
The solution set cannot contain repeated combinations.

Insert picture description here

Analysis:

First reference:
Seeking Subset I
Seeking Subset II

This question is only added a judgment subset size and condition.

We can follow the method of seeking subset II, first find out all the subsets, and then find the element sum as a subset of the target.

But again because:
Insert picture description hereso we can
Insert picture description here

Code:

class Solution {
    
    
    public List<List<Integer>> combinationSum2(int[] nums, int target) {
    
    
    List<List<Integer>> ans = new ArrayList<>();
    Arrays.sort(nums); //排序
    getAns(nums, 0, new ArrayList<>(), ans,0,target);
    return ans;
}

private void getAns(int[] nums, int start, ArrayList<Integer> temp, List<List<Integer>> ans, int sum,int target) {
    
    
     if(target==0){
    
    
       ans.add(new ArrayList<>(temp));
      return;
     }
    for (int i = start; i < nums.length; i++) {
    
    
        //和上个数字相等就跳过
        if (i > start && nums[i] == nums[i - 1]) {
    
    
            continue;
        }
        sum=sum+nums[i];
        if(sum>target){
    
      //剪枝操作
              return;
        }
         temp.add(nums[i]);
        if(target==sum){
    
       //符合要求,加入返回结果
           ans.add(new ArrayList<>(temp));
        }
        getAns(nums, i + 1, temp, ans,sum,target);
        temp.remove(temp.size() - 1);
        sum=sum-nums[i];

    }
}
}

Source: LeetCode
Link: https://leetcode-cn.com/problems/combination-sum-ii
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_42120561/article/details/114270944