码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 39-Combination Sum(medium)

时间:2018-09-23 00:18:57      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:one   moment   tracking   sum   leetcode   cat   ati   hose   func   

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

backtracking

first sort the array, make it low to high

cases:

use a function:(a list to store all combinations, a tinylist store the trial at the moment, a int  i store start place of numbers in candidates that we can add to the tinylist(the biggest index of number in tinylist) (avoid duplicates(permutaion))

 1. target<0, return;

 2. target=0, add tinylist to list and return;

 3. start from i, iterate through i->end, everytime add one number to the tinylist, and continue backtracking, remember to remove the added one after backtracking

 

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> list=new ArrayList<>();
        if(target==0||candidates.length==0) return list;
        Arrays.sort(candidates);
        findSum(candidates, list, new ArrayList<Integer>(), target, 0);
        return list;
    }
    public void findSum(int[] candidates, List<List<Integer>> list, List<Integer> tinyList, int target, int index){
        if(target<0) return;
        else if(target==0){
            list.add(new ArrayList<>(tinyList)); return;
        } 
        for(int i=index;i<candidates.length;i++){
            tinyList.add(candidates[i]);
            findSum(candidates, list, tinyList, target-candidates[i], i);
            tinyList.remove(tinyList.size()-1);
        }
    }
}

 

leetcode 39-Combination Sum(medium)

标签:one   moment   tracking   sum   leetcode   cat   ati   hose   func   

原文地址:https://www.cnblogs.com/yshi12/p/9691626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!