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; } }}
- LeetCode_40---Combination Sum II
- LeetCode_40 Combination Sum II
- leetcode_40. Combination Sum II ? 待解决
- Combination Sum && Combination Sum II
- Combination Sum Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- [LeetCode] Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- Combination Sum II
- how to add external library in qt under ubuntu
- LeetCode_37 Sudoku Solver
- 论----计算机程序智能化
- LeetCode_39 Combination Sum
- MSB&LSB与Endianness
- LeetCode_40 Combination Sum II
- 【Leetcode】Copy List with Random Pointer
- how to get current path in qt
- xfire客户端调用cxf服务端,一直报错
- hdu 1806 RMQ
- Leetcode 252Meeting Rooms
- Leetcode 253Meeting Rooms II
- Leetcode 296Best Meeting Point
- 202——砖块染色问题 Blocks (POJ 3734)