Leet Code 40 - Combination Sum II - 组合和 - Java
2016-06-21 00:00
459 查看
摘要: Leet Code 40 - Combination Sum II - 组合和 - Java
问题原始链接 https://leetcode.com/problems/combination-sum-ii
给定一个数集C和一个目标数T,找到C中所有和等于T的组合。C中的每个数在组合中最大只允许使用一次。
注意:
所有的数(包括目标数)都是正整数。
结果中不允许有重复组合。
例如,给定数集 [10,1,2,7,6,1,5],目标数8
[
[1,7]
[1,2,5]
[2,6]
[1,1,6]
]
问题原始链接 https://leetcode.com/problems/combination-sum-ii
给定一个数集C和一个目标数T,找到C中所有和等于T的组合。C中的每个数在组合中最大只允许使用一次。
注意:
所有的数(包括目标数)都是正整数。
结果中不允许有重复组合。
例如,给定数集 [10,1,2,7,6,1,5],目标数8
[
[1,7]
[1,2,5]
[2,6]
[1,1,6]
]
public class Solution { public static List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (candidates == null || candidates.length == 0) { return result; } Arrays.sort(candidates); List<Integer> temp = new ArrayList<Integer>(); Map<Integer, Integer> count = count(candidates); combinationSum(candidates, target, count, candidates.length - 1, temp, result); return result; } private static Map<Integer, Integer> count(int[] candidates) { Map<Integer, Integer> result = new HashMap<Integer, Integer>(); for (Integer i : candidates) { Integer c = result.get(i); result.put(i, c == null ? Integer.valueOf(1) : (c + 1)); } return result; } private static void combinationSum(int[] candidates, int target, Map<Integer, Integer> count, int i, List<Integer> temp, List<List<Integer>> result) { int c = count.get(candidates[i]); for (int j = Math.min(target / candidates[i], c); j >= 0; j--) { if (i == 0) { if (target == candidates[i] * j) { result.add(add(temp, candidates[i], j)); } } else { List<Integer> t = add(temp, candidates[i], j); if (target == j * candidates[i]) { result.add(t); } else { int k = i - c; if (k >= 0) { combinationSum(candidates, target - j * candidates[i], count, k, t, result); } } } } } private static List<Integer> add(List<Integer> temp, int x, int j) { List<Integer> t = new ArrayList<Integer>(temp); for (int k = 0; k < j; k++) { t.add(x); } return t; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解