【LeetCode】40.Combination Sum II(Medium)解题报告

来源:互联网 发布:2016中日贸易数据 编辑:程序博客网 时间:2024/05/16 06:26

【LeetCode】40.Combination Sum II(Medium)解题报告

题目地址: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]]

  这道题要求数字不可以多次利用,不要求数字的个数。combo(res,candidates,target-candidates[i],tempList,i+1);这一行很重要,与前一题代码只有此处变为i+1;

Solution:

//组合套路题class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        List<List<Integer>> res = new ArrayList<>();        List<Integer> tempList = new ArrayList<>();        Arrays.sort(candidates);        combo(res,candidates,target,tempList,0);        return res;    }    public void combo(List<List<Integer>> res,int[] candidates,int target,List<Integer> tempList,int index){        if(target<0){            return;        }else if(target==0){            res.add(new ArrayList<>(tempList));        }else{            for(int i=index;i<candidates.length;i++){                tempList.add(candidates[i]);                combo(res,candidates,target-candidates[i],tempList,i+1);                //回溯                tempList.remove(tempList.size()-1);                //结果去重                while(i<candidates.length-1 && candidates[i]==candidates[i+1]) i++;            }        }    }}

Date:2017年12月12日

原创粉丝点击