/* Author: Annie Kim, anniekim.pku@gmail.com Date: May 25, 2013 Problem: Combination Sum Difficulty: Easy Source: http://leetcode.com/onlinejudge#question_39 Notes: 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. Elements in a combination (a1, a2, .. , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak). 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] Solution: Sort & Recursion. */ public class Solution { public List> combinationSum(int[] candidates, int target) { List> res = new ArrayList>(); Arrays.sort(candidates); ArrayList path = new ArrayList(); combinationSumRe(candidates, target, 0, path, res); return res; } void combinationSumRe(int[] candidates, int target, int start, ArrayList path, List> res) { if (target == 0) { ArrayList p = new ArrayList(path); res.add(p); return; } for (int i = start; i < candidates.length && target >= candidates[i]; ++i) { path.add(candidates[i]); combinationSumRe(candidates, target-candidates[i], i, path, res); path.remove(path.size() - 1); } } }