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

Java [Leetcode 40]Combination Sum II

时间:2015-12-04 22:59:19      阅读:401      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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, 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] 

解题思路:

跟前一个类似,不过每次选好当前元素后,就直接选下一个位置的元素了。并且在每次选元素之前,保证这次的元素与上次的元素不重合。

代码如下:

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates,
			int target) {
		Arrays.sort(candidates);
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		getResult(result, new ArrayList<Integer>(), candidates, target, 0);
		return result;
	}

	public void getResult(List<List<Integer>> result,
			List<Integer> current, int[] candiates, int target, int start) {
		if (target > 0) {
			for (int i = start; i < candiates.length && target >= candiates[i]; i++) {
				if (i > start && candiates[i] == candiates[i - 1])
					continue;
				current.add(candiates[i]);
				getResult(result, current, candiates, target - candiates[i],
						i + 1);
				current.remove(current.size() - 1);
			}
		} else if (target == 0) {
			result.add(new ArrayList<Integer>(current));
		}
	}
}

  

Java [Leetcode 40]Combination Sum II

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/5020651.html

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