Leetcode 40. Combination Sum II

来源:互联网 发布:幻想乡网络手游 编辑:程序博客网 时间:2024/05/19 01:59
public class Solution {    public static void backTrack(List<Integer> tmp, List<List<Integer>> res, int start, int target, int[] nums) {        if (target < 0) return;        else if (target == 0) res.add(new ArrayList<>(tmp));        else {            for(int i=start; i<nums.length; i++) {                // skip duplicates                if (i>start && nums[i] == nums[i-1]) continue;                tmp.add(nums[i]);                backTrack(tmp, res, i+1, target-nums[i], nums);                tmp.remove(tmp.size()-1);            }        }    }        public List<List<Integer>> combinationSum2(int[] candidates, int target) {        // sort the array to filter out duplicates        Arrays.sort(candidates);        List<List<Integer>> res = new ArrayList<>();        backTrack(new ArrayList<>(), res, 0, target, candidates);        return res;    }}

0 0
原创粉丝点击