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

廉价感情. 提交于 2019-11-29 08:01:38

【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日

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!