【leetcode刷题笔记】Combination Sum II

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

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

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 


 

Combination Sum的差别就是上面红色的那行字,只要把递归时候的起点由i改为i+1即可,参见下列代码中高亮的部分:

代码如下:

复制代码
 1 public class Solution {
 2     private void combiDfs(int[] candidates,int target,List<List<Integer>> answer,List<Integer> numbers,int start){
 3         if(target == 0){
 4             answer.add(new ArrayList<Integer>(numbers));
 5             return;
 6         }
 7         
 8         int prev = -1;
 9         
10         for(int i = start;i < candidates.length;i++){
11             if(candidates[i] > target)
12                 break;
13             if(prev != -1 && prev == candidates[i])
14                 continue;
15             
16             numbers.add(candidates[i]);
17             combiDfs(candidates, target-candidates[i], answer, numbers,i+1);
18             numbers.remove(numbers.size()-1);
19             
20             prev = candidates[i];
21         }
22     }
23     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
24         List<List<Integer>> answer = new ArrayList<List<Integer>>();
25         List<Integer> numbers = new ArrayList<Integer>();
26         Arrays.sort(candidates);
27         combiDfs(candidates, target, answer, numbers,0);
28         
29         return answer;
30         
31     }
32 }
复制代码
posted @   SunshineAtNoon  阅读(175)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示