LeetCode_40 Combination Sum II

来源:互联网 发布:windows ble蓝牙开发 编辑:程序博客网 时间:2024/04/28 07:11

Link to the original problem: 这里写链接内容
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]

related problem: 39 Combination Sum 这里写链接内容

The only difference is each element can be used once rather than multiple times. So we add another parameter into helper function lastIndex, if one element equals to the previous one and lastIndex is not the previous index, we continue to next element in this array.

Here is the solution code:

public class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        List<List<Integer>> res = new ArrayList<List<Integer>>();        if(candidates == null || candidates.length == 0) return res;        Arrays.sort(candidates);        List<Integer> cur = new ArrayList<Integer>();        helper(res, cur, -1, 0, candidates, target);        return res;    }    private void helper(List<List<Integer>> res, List<Integer> cur, int lastIndex, int start, int[] C, int target){        if(target == 0){            res.add(new ArrayList<Integer>(cur));            return;        }        for(int ii = start; ii < C.length; ii++){            if( ii > 0 && (C[ii] == C[ii-1] && lastIndex != ii-1) ) continue;            if(C[ii] <= target){                cur.add(C[ii]);                helper(res, cur, ii, ii+1, C, target-C[ii]);                cur.remove(cur.size()-1);            }            else break;        }    }}
0 0
原创粉丝点击