[leetcode]40. Combination Sum II(Java)

来源:互联网 发布:编程有什么用 编辑:程序博客网 时间:2024/05/23 22:51

leetcode:https://leetcode.com/problems/combination-sum-ii/#/description

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]]

Subscribe to see which companies asked this question.


Java Code:

package go.jacob.day621;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Demo4 {public List<List<Integer>> combinationSum2(int[] candidates, int target) {List<List<Integer>> res = new ArrayList<List<Integer>>();if (candidates == null || candidates.length < 1)return res;Arrays.sort(candidates);backtrack(candidates, target, res, new ArrayList<Integer>(), 0);return res;}// 如果不加参数start,会出现:input:[2,3,6,7]7// 结果:[[2,2,3],[2,3,2],[3,2,2],[7]]instead of [[2,2,3],[7]]的情况private void backtrack(int[] nums, int target, List<List<Integer>> res, ArrayList<Integer> list, int start) {if (target == 0) {res.add(new ArrayList<Integer>(list));return;}for (int i = start; i < nums.length && target >= nums[i]; i++) {if(i>start&&nums[i]==nums[i-1])continue;list.add(nums[i]);backtrack(nums, target - nums[i], res, list, i + 1);list.remove(list.size() - 1);}}}



原创粉丝点击