leetcode 40. Combination Sum II

一 题目

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates 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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

Accepted  249,560  Submissions 574,355

二 分析

  medium级别难度,求数组里面组成target元素的组合。跟上个题目  leetcode 39. Combination Sum 差不多,一个套路,区别在于本题要求不重复。

还是使用DFS 深度优先的递归方法,为了能连续跳过重复的数,这里我们必须先排序。为了不重复元素比如数组里面有3个2,结果里面最多也是3个2,需要额外记录下使用过的索引位置。

public static void main(String[] args) {
		// TODO Auto-generated method stub
       int[] nums = {10,1,2,7,6,1,5};
       List> res = combinationSum2(nums,8);
       System.out.println(JSON.toJSON( res)) ;
	}

	public static List> combinationSum2(int[] candidates, int target) {
		
		List> res = new ArrayList();
		List tlist = new ArrayList();
		List usedlist = new ArrayList();
		//先排序
		Arrays.sort(candidates);
	     //拆分rule
		combin( candidates,  target,0,tlist,usedlist,res);				
		return res;        

    }
	
	private static void combin(int[] arrays,int target,int index,List temp,List used,List> result){
		
		//超范围,不匹配
		if( target<0){
			return;
		}//匹配,加入结果集
		else if(target ==0){
			if(!result.contains(temp)){
				result.add(new ArrayList( temp));
			}
			used = new ArrayList( );
		}else{
			//target){
					break;
				}
				//先放入
				if(!used.contains(i)){
				temp.add(arrays[i]);
				used.add(i);
				//尝试匹配
				combin(arrays,target-arrays[i], i, temp,used,result);
				//在取出:最后加入的
				temp.remove(temp.size()-1);
				used.remove(used.size()-1 );
				}
			}			
		}		
	}

Runtime: 6 ms, faster than 51.90% of Java online submissions forCombination Sum II.

Memory Usage: 38.6 MB, less than 83.16% of Java online submissions forCombination Sum II.

时间复杂度 O(N!)

 

你可能感兴趣的:(数组,Combination,Sum,II,算法,DFS,递归,leetcode)