Leetcode: Combination Sum II
来源:互联网 发布:淘宝买伟哥 编辑:程序博客网 时间:2024/05/01 00:23
Problem:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.
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]
Solution:
DFS and recursion
The main difference between II and I is that in II, in each recursion, each value can only be selected once.
code
public class Solution { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) { ArrayList<Integer> list = new ArrayList<Integer>(); if (candidates == null || candidates.length == 0) { result.add(list); return result; } int length = candidates.length; Arrays.sort(candidates); selectCombination(candidates,0,length,list, target); return result; } public void selectCombination(int[] candidates, int k, int length, ArrayList<Integer> list, int target) { if (target == 0) { ArrayList<Integer> tmp = new ArrayList<Integer>(list); result.add(tmp); } if (target < 0 || k == length) return; for (int i = k; i < length; i++) { if (i != k && candidates[i] == candidates[i - 1]) continue; list.add(candidates[i]); selectCombination(candidates, i + 1, length, list, target - candidates[i]); list.remove(list.size() - 1); } } }
0 0
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- [LeetCode] Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- LeetCode: Combination Sum II
- leetcode Combination Sum II
- [LeetCode]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】
- [LeetCode] Combination Sum II
- OC——copy语法的基本使用
- Yii登陆添加验证码
- HDU 4003 Find Metal Mineral 树形DP
- Android 一步一步实现版本自动更新(第二步 下载和安装apk)
- Android中的Handler的具体用法
- Leetcode: Combination Sum II
- 灰度图像--图像分割 阈值处理综述
- Pro Android学习笔记(八九):了解Handler(3):延迟执行小例子
- 线程的状态间转换
- 控制台输入响应
- 使用Android Studio遇到的问题
- poj 1144 Network
- 无能的很可能正是我们自己
- php分页类实现