码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] 40. Combination Sum II Java

时间:2017-06-05 12:38:29      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:and   contain   ++   solution   code   add   nat   tin   sed   

题目:

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.
  • 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]
]

题意及分析:这道题比上一题多了一个约束条件,即元素不能重复使用,所以只需要在下一次回溯时将起始点的位置加一即可。具体见代码。

代码:

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<Integer> array= new ArrayList<>();
        List<List<Integer>> list = new ArrayList<>();
        int start=0;
        int remain=target;
        backTracking(list,array,candidates,start,remain);
        return list;
    }
	
	public void backTracking(List<List<Integer>> list,List<Integer> array,int[] candidates,int start,int remain) {
		if(remain<0)
			return;
		else if(0==remain){	//有解
			list.add(new ArrayList<>(array));
		}else{
			for(int i=start;i<candidates.length;i++){
				if(i>start&&candidates[i]==candidates[i-1]) continue;  //去重
				array.add(candidates[i]);
				backTracking(list, array, candidates, i+1, remain-candidates[i]);  //这里是i+1
				array.remove(array.size()-1);
			}
		}
		return;
	}
}

  

[LeetCode] 40. Combination Sum II Java

标签:and   contain   ++   solution   code   add   nat   tin   sed   

原文地址:http://www.cnblogs.com/271934Liao/p/6944002.html

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