40. 组合总和 II-LeetCode

博客分享回溯和剪枝算法使用心得,强调要想全剪枝条件以节省时间,去重时尽量不用set,让代码更优雅。还建议将条件写得紧凑,在一个递归里处理并改变条件,以减少代码量。

心得:主要用到回溯和剪枝,一定要把剪枝的条件想全了,要不然时间会多很多

这里去重的地方要好好注意一下,如何去重的,能不用set尽量不用,比较优雅。

尽量把条件写的紧凑一点,能在一个递归里处理的在一个递归里处理,把条件改变

写在递归方法里,然后再去处理,这样代码量小,而且优雅。

 1 class Solution {
 2       public List<List<Integer>> combinationSum2(int[] candidates, int target){
 3            LinkedList<List<Integer>> list=new LinkedList<>();
 4             if(candidates==null||candidates.length==0)
 5                 return list;
 6             Arrays.sort(candidates);
 7             rec(0,list,new LinkedList<Integer>(),candidates,target);
 8             return list;
 9         }
10     public void rec(int index,LinkedList<List<Integer>> list,LinkedList<Integer> tmp,int[] candidates,int target)
11        {
12          if(target<0)
13              return;
14          else if(target==0)
15          {        
16              list.add(new LinkedList(tmp));
17              return;
18          }
19          else
20          {
21              for(int i=index;i< candidates.length&&candidates[i]<=target;i++)//这个剪枝条件就可以提高
//速度
22 { 23 if(i!=index&&candidates[i]==candidates[i-1]) 24 continue; 25 tmp.add(candidates[i]); 26 rec(i+1,list,tmp,candidates,target-candidates[i]); 27 tmp.removeLast(); 28 } 29 } 30 } 31 }

 

转载于:https://www.cnblogs.com/pc-m/p/10954734.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值