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

LeetCode-Combination Sum

时间:2016-08-11 07:26:53      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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

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

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7, 
A solution set is: 
[
  [7],
  [2, 2, 3]
]

对于这种backtracking的题目, 还是得了解选择,限制,和结束的条件分别是什么。

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if(candidates==null || candidates.length==0){
            return null;
        }
        //Arrays.sort(candidates);
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        List<Integer> item=new ArrayList<Integer>();
        int len=candidates.length;
        backTracking(candidates, target, 0, item, res);
        return res;
    }
    public void backTracking(int[] candidates, int target, int start, List<Integer> item, List<List<Integer>> res){
        if(target<0){
            return;
        }
        
        if(target==0){
            res.add(new ArrayList<Integer>(item));
            return;
        }
        for(int i=start; i<candidates.length; i++){
            if(i>0 && candidates[i]==candidates[i-1]){
                continue;
            }
            item.add(candidates[i]);
            backTracking(candidates, target-candidates[i], i, item, res);
    
            //走到死路了,就回复到上一个状态
            item.remove(item.size()-1);
        }
    }
    
}           

 

LeetCode-Combination Sum

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5759507.html

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