Leetcode-40. Combination Sum II

来源:互联网 发布:淘宝电子发票如何生成 编辑:程序博客网 时间:2024/06/05 07:25

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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]]
这个题目就是39的调整而已,需要做的就是将递归条件改动一下即可。Your runtime beats 61.65% of java submissions.

public class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        Arrays.sort(candidates);        List<List<Integer>> result = new ArrayList<List<Integer>>();        getResult(result, new ArrayList<Integer>(), candidates, target, 0);        return result;    }    private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){    if(target > 0){    for(int i = start; i < candidates.length && target >= candidates[i]; i++){    cur.add(candidates[i]);    getResult(result, cur, candidates, target - candidates[i], i+1);    cur.remove(cur.size() - 1);    while(i < candidates.length - 1 && candidates[i] == candidates[i + 1]) i ++;    }//for    }//if    else if(target == 0 ){    result.add(new ArrayList<Integer>(cur));    }//else if    }}







0 0
原创粉丝点击