LeetCode 40. Combination Sum II
来源:互联网 发布:撕衣服软件下载 编辑:程序博客网 时间:2024/06/01 08:05
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.
- 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]]
本来想着用Set来去除重,结果TLE啦。那只能在递归中的for循环里面去重了。
public class Solution { private void helper(int[] candidates, int pos, int target, Stack<Integer> stack, List<List<Integer>> list){ if(target < 0) return ; if(target == 0){ List<Integer> row = new ArrayList<>(); for(int i:stack){ row.add(i); } list.add(row); return; } int prev = 0; for(int i=pos; i<candidates.length; i++){ if(candidates[i] == prev) continue; prev =candidates[i]; stack.push(candidates[i]); helper(candidates, i+1, target-candidates[i], stack, list); stack.pop(); } } public List<List<Integer>> combinationSum2(int[] candidates, int target) { Stack<Integer> stack = new Stack<>(); List<List<Integer>> lists = new ArrayList<>(); Arrays.sort(candidates); helper(candidates, 0, target, stack, lists); return lists; }}
0 0
- [LeetCode]40.Combination Sum II
- LeetCode --- 40. Combination Sum II
- LeetCode 40.Combination Sum II
- [Leetcode] 40. Combination Sum II
- LeetCode 40. Combination Sum II
- [leetcode] 40. Combination Sum II
- 40. Combination Sum II LeetCode
- leetcode 40. Combination Sum II
- Leetcode 40. Combination Sum II
- LeetCode 40. Combination Sum II
- leetcode 40. Combination Sum II
- LeetCode 40. Combination Sum II
- LeetCode 40. Combination Sum II
- LeetCode *** 40. Combination Sum II
- 【LeetCode】40. Combination Sum II
- leetcode 40. Combination Sum II
- LeetCode - 40. Combination Sum II
- [LeetCode] 40. Combination Sum II
- 定时刷新lucene缓存配置方式
- php读取文件
- 可用于获取百度贴吧的帖子中的Email地址的Python脚本
- poj 1654
- 程序员的30本书——经典中的经典
- LeetCode 40. Combination Sum II
- 安卓获取顶层应用的包名
- android:layout_gravity 和 android:gravity 的区别
- html5 读取本地文件说明和实例
- windows7下makefile例程
- 玩转iOS开发:《iOS设计模式 — 代理模式》
- 企业应该如何运用商业智能
- sql server 跨数据库复制表
- 伟大的程序员是怎样炼成的?