zoukankan      html  css  js  c++  java
  • Java [Leetcode 40]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 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));
    		}
    	}
    }
    

      

  • 相关阅读:
    2018-8-10-wpf-绑定-DataGridTextColumn-
    行踪隐藏 代理助手
    木马防杀 花指令 OllyDbg
    木马加壳
    elsave.exe日志清除
    黑客小工具
    WinRAR捆绑木马
    网页木马使用
    灰鸽子商业版用法
    黑洞远程连接
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5020651.html
Copyright © 2011-2022 走看看