39. Combination Sum 40 Combination Sum 2(Array, DFS)

本文深入探讨了组合求和问题的两种变体:允许元素重复使用的组合求和(Combination Sum)与限制元素仅能使用一次的组合求和2(Combination Sum 2)。通过详细的代码示例和思路讲解,读者将理解如何使用深度优先搜索(DFS)策略来解决这两类问题,同时避免生成重复的解决方案集合。

39. Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7
A solution set is:
[
  [7],
  [2,2,3]
]

思路:依旧使用DFS,因为每个元素可以重复使用多次,所以调用的时候从当前位置开始。用target保存当前值,如果小于零就去掉最后一个元素并回溯,如果等于零就加入res,如果大于零就继续递归。一开始我将循环每次都从0开始,就会出现【2,2,3】,【2,3,2】,【3,2,2】的结果。因此首先对数组排序,然后向前搜寻不重复。

 public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates==null ||candidates.length==0)
            return res;
        List<Integer> tmp = new ArrayList<Integer>();
        Arrays.sort(candidates);
        doCombine(candidates, target,0, tmp, res);
        return res;
    }
    
    private void doCombine(int[] nums, int target, int pos,List<Integer> tmp, List<List<Integer>> res){
        for(int i=pos;i<nums.length;i++){
            target = target - nums[i];
            tmp.add(nums[i]);
            if(target<=0){
                if(target==0)
                    res.add(new ArrayList<Integer>(tmp));
                tmp.remove(tmp.size()-1);
                target = target + nums[i];
                return;
            }          
            doCombine(nums,target,i,tmp,res);
            tmp.remove(tmp.size()-1);
            target = target + nums[i];
        }
    }

40. Combination Sum 2

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

思路:

区别在于每个元素只能用一次。所以递归是应该是i+1.

为了避免重复,首先对数组排序,然后连续两个相同元素会产生相同结果,所以奖后一个元素跳过,这里的方法和permutation2中用到的一样。

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates==null ||candidates.length==0)
            return res;
        List<Integer> tmp = new ArrayList<Integer>();
        Arrays.sort(candidates);
        doCombine(candidates, target,0, tmp, res);
        return res;
    }
    private void doCombine(int[] nums, int target, int pos,List<Integer> tmp, List<List<Integer>> res){
        for(int i=pos;i<nums.length;i++){
            target = target - nums[i];
            tmp.add(nums[i]);
            if(target<=0){
                if(target==0)
                    res.add(new ArrayList<Integer>(tmp));
                tmp.remove(tmp.size()-1);
                target = target + nums[i];
                return;
            }                      
            doCombine(nums,target,i+1,tmp,res);//注意是i+1
            tmp.remove(tmp.size()-1);
            target = target + nums[i];
            while(i<nums.length-1 && nums[i]==nums[i+1])
                i++;//跳过相同结果
        }
    }

 

### LeetCode Top 100 Popular Problems LeetCode provides an extensive collection of algorithmic challenges designed to help developers prepare for technical interviews and enhance their problem-solving skills. The platform categorizes these problems based on popularity, difficulty level, and frequency asked during tech interviews. The following list represents a curated selection of the most frequently practiced 100 problems from LeetCode: #### Array & String Manipulation 1. Two Sum[^2] 2. Add Two Numbers (Linked List)[^2] 3. Longest Substring Without Repeating Characters #### Dynamic Programming 4. Climbing Stairs 5. Coin Change 6. House Robber #### Depth-First Search (DFS) / Breadth-First Search (BFS) 7. Binary Tree Level Order Traversal[^3] 8. Surrounded Regions 9. Number of Islands #### Backtracking 10. Combination Sum 11. Subsets 12. Permutations #### Greedy Algorithms 13. Jump Game 14. Gas Station 15. Task Scheduler #### Sliding Window Technique 16. Minimum Size Subarray Sum 17. Longest Repeating Character Replacement #### Bit Manipulation 18. Single Number[^1] 19. Maximum Product of Word Lengths 20. Reverse Bits This list continues up until reaching approximately 100 items covering various categories including but not limited to Trees, Graphs, Sorting, Searching, Math, Design Patterns, etc.. Each category contains multiple representative questions that cover fundamental concepts as well as advanced techniques required by leading technology companies when conducting software engineering candidate assessments. For those interested in improving logical thinking through gaming activities outside traditional study methods, certain types of video games have been shown beneficial effects similar to engaging directly within competitive coding platforms [^4]. --related questions-- 1. How does participating in online coding competitions benefit personal development? 2. What specific advantages do DFS/BFS algorithms offer compared to other traversal strategies? 3. Can you provide examples illustrating how bit manipulation improves performance efficiency? 4. In what ways might regular participation in programming contests influence job interview success rates? 5. Are there any notable differences between solving problems on paper versus implementing solutions programmatically?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值