• 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));
    		}
    	}
    }
    

      

  • 相关阅读:
    WF4.0 自定义CodeActivity与Bookmark<第三篇>
    WF4 常用类<第二篇>
    WF4.0 Activities<第一篇>
    WWF3常用类 <第十一篇>
    WWF3XOML方式创建和启动工作流 <第十篇>
    element-ui表格显示html格式
    tail -f 加过滤功能
    vue 遇到防盗链 img显示不出来
    python No module named 'urlparse'
    grep awk 查看nginx日志中所有访问的ip并 去重
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5020651.html
Copyright © 2020-2023  润新知