Combination Sum II leetcode java

寻找唯一组合求和等于目标数
本博客探讨了一个算法问题,即从候选数字集中找到所有唯一组合,这些组合的和等于给定的目标数,同时确保每个数字仅使用一次。通过实现一个递归函数并引入visited数组来标记已使用的元素,解决了重复元素的问题。示例展示了如何解决这个问题,并提供了代码实现。

题目

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

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, a1a2 ≤ … ≤ 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本质的差别就是当前已经遍历过的元素只能出现一次。

所以需要给每个candidate一个visited域,来标识是否已经visited了。

当回退的时候,记得要把visited一起也回退了。

代码如下:

 1     public static ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {  
 2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();  
 3         ArrayList<Integer> item = new ArrayList<Integer>();
 4         if(candidates == null || candidates.length==0)  
 5             return res; 
 6             
 7         Arrays.sort(candidates);  
 8         boolean [] visited = new boolean[candidates.length];
 9         helper(candidates,target, 0, item ,res, visited);  
10         return res;  
11     }  
12     
13     private static void helper(int[] candidates, int target, int start, ArrayList<Integer> item,   
14     ArrayList<ArrayList<Integer>> res, boolean[] visited){  
15         if(target<0)  
16             return;  
17         if(target==0){  
18             res.add(new ArrayList<Integer>(item));  
19             return;  
20         }
21         
22         for(int i=start;i<candidates.length;i++){
23             if(!visited[i]){
24                 if(i>0 && candidates[i] == candidates[i-1] && visited[i-1]==false)//deal with dupicate
25                     continue;  
26                 item.add(candidates[i]);
27                 visited[i]=true;
28                 int newtarget = target - candidates[i];
29                 helper(candidates,newtarget,i+1,item,res,visited);  
30                 visited[i]=false;
31                 item.remove(item.size()-1);  
32             }
33         }  
34     } 

 

转载于:https://www.cnblogs.com/springfor/p/3886057.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值