您的位置:首页 > 其它

Combination Sum II 无序数组中找组合(每个元素只能用一次)使得和为target@LeetCode@LeetCode

2013-11-21 12:40 603 查看
和上一题思想一样,区别在于每个元素只能用一次,所以start的位置也要改变。

另外一个问题是如何处理返回大集合中有重复子集合的问题。最容易想到的就是用HashSet来过滤一遍,参考了http://blog.csdn.net/u011095253/article/details/9158423

的大作后发现有一种更绿色的方法,就是多用一个while循环跳过相同的元素!这个技巧在很多情况下都很好用的!

package Level4;

import java.util.ArrayList;
import java.util.Arrays;

/**
* Combination Sum II
*
*  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 S40 {

public static void main(String[] args) {
int[] num = {10,1,2,7,6,1,5};
int target = 8;
System.out.println(combinationSum2(num, target));
}

public static ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
ArrayList<ArrayList<Integer>> ret = new  ArrayList<ArrayList<Integer>>();
ArrayList<Integer> al = new ArrayList<Integer>();
Arrays.sort(num);
dfs(num, target, 0, ret, al);
return ret;
}

public static void dfs(int[] num, int remain, int start, ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> al){
if(remain == 0){
ret.add(new ArrayList<Integer>(al));
return;
}

for(int i=start; i<num.length; i++){
int rest = remain - num[i];
if(rest < 0){
return;
}
al.add(num[i]);
dfs(num, rest, i+1, ret, al);	// 因为不能重复使用元素,所以每次用完后就跳过
al.remove(al.size()-1);

// 跳过相同的元素
while(i<num.length-1 && num[i]==num[i+1]){
i++;
}
}
}
}


注意:

            while(i+1<num.length && num[i+1]==num[i]){

                i++;

            }

这里i只能和i+1比较,因为i是从0开始的,所以如果与i-1比较则会因为越界而无法继续比较。

public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> al = new ArrayList<Integer>();
Arrays.sort(num);
dfs(num, target, 0, al, ret);
return ret;
}

public void dfs(int[] num, int target, int pos, ArrayList<Integer> al, ArrayList<ArrayList<Integer>> ret){
if(target < 0){
return;
}
if(target == 0){
ret.add(new ArrayList<Integer>(al));
return;
}

for(int i=pos; i<num.length; i++){
al.add(num[i]);
dfs(num, target-num[i], i+1, al, ret);
al.remove(al.size()-1);

while(i+1<num.length && num[i+1]==num[i]){
i++;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: