码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Combination Sum II

时间:2015-09-29 01:04:38      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/combination-sum-ii/

本题与Combination Sum非常相似,不同就在于本题不可以重复使用元素。其实只是递归时,start的参数更改为i+1即可。

Note: 1. 即使本题不可以使用重复元素但也需要小心res 里加了重复的item. e.g. target = 1, candidates = [1,1], res中会出现两个[1]. 所以在加入res前需校验res中是否已有相同item.

这个方法同样适用于Combination Sum.

AC Java:

 1 public class Solution {
 2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         if(candidates == null || candidates.length == 0){
 5             return res;
 6         }
 7         Arrays.sort(candidates);
 8         helper(candidates,target,0,new ArrayList<Integer>(),res);
 9         return res;
10     }
11     private void helper(int[] candidates, int target, int start, List<Integer> item, List<List<Integer>> res){
12         if(target == 0){
13             if(!res.contains(item)){
14                 res.add(new ArrayList<Integer>(item));
15             }
16             return;
17         }
18         if(target < 0){
19             return;
20         }
21         for(int i = start; i<candidates.length; i++){
22             item.add(candidates[i]);
23             helper(candidates,target-candidates[i],i+1,item,res);
24             item.remove(item.size()-1);
25         }
26     }
27 }

 

LeetCode Combination Sum II

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4845293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!