LeetCode-Combination Sum
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); } } }
posted on 2016-08-11 06:14 IncredibleThings 阅读(160) 评论(0) 编辑 收藏 举报