1. 程式人生 > >leetCode 40.Combination Sum II(組合總和II) 解題思路和方法

leetCode 40.Combination Sum II(組合總和II) 解題思路和方法

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] 

思路:此題和Combination Sum類同,而且很多程式碼都可以複用,僅僅改變幾處不大的變化和增加了一個去處重複項的函式。

具體程式碼如下:

public class Solution {

    public List<List<Integer>> combinationSum2(int[] a, int t) {
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		List<List<Integer>> newList = new ArrayList<List<Integer>>();
		list = combinationSum1(a,t);
        Set<List<Integer>> set = new HashSet<List<Integer>>();//去除重複
        for(int i = 0; i < list.size();i++){
        	if(set.add(list.get(i))){//沒有重複
        		newList.add(list.get(i));//新增新的列表
        	}
        }
        return newList;
	}
	
    public List<List<Integer>> combinationSum1(int[] a, int t) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Arrays.sort(a);//陣列排序
        //各種特殊情況
        if(a.length == 0 || a[0] > t)
            return list;

        int len = 0;
        boolean isAdd = false;//控制與t相等的數只新增一次
        for(int i = 0; i< a.length;i++){
            if(a[i] == t){
                if(!isAdd){//如果未新增
                    List<Integer> al = new ArrayList<Integer>();
                    al.add(t);
                    list.add(al);
                    isAdd = true;//標記已新增
                }
            }else if(a[i] < t){//只要比target小的值,大的值肯定不滿足,排除
                a[len++] = a[i];//新陣列
            }
        }
        //只存在a[0] < target 或 a[0] > target
        if(a[0] > t)//肯定已沒有符合要求的組合
            return list;
        //a[0] < target
        
        for(int i = 0; i < len; i++){//迴圈搜尋符合要求的數字組合
        	int[] b = Arrays.copyOfRange(a, i+1, len);//不含>=t資料的新陣列
        	if(a[i] > t)//如果a[i],肯定以後的資料已不符合,返回
        		break;
            //相等於已經有了一個值a[0]了    
            List<List<Integer>> newList = new ArrayList<List<Integer>>();
            if(i < len -1)
            	newList = combinationSum1(b,t-a[i]);
            if(newList.size() > 0){//裡面有符合要求的資料
                for(int j = 0; j < newList.size();j++){
                    newList.get(j).add(a[i]);//新返回的各個值新增a[0]
                	Collections.sort(newList.get(j));//排序
                    list.add(newList.get(j));//最終新增
                }
            }
        }
        return list;
    }
}