This question is typically a DP one. It might be the simplest one among those DP questions I have solved.
Basic idea is to start from the largest element in candidates array, then try to use this one as many times as possible to let remainNum get 0. If remainNum gets 0, then remove latest added one, and lets try next number in array, until all numbers are traversed; otherwise, add new number into combination,
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
if((target <= 0) || (candidates.length == 0) || (target < candidates[0])) return res;
ArrayList<Integer> comb = new ArrayList<Integer>();
findCombOfSums(res,comb,candidates, candidates.length - 1, target);
return res;
}
public void findCombOfSums(ArrayList<List<Integer>> res, ArrayList<Integer> comb,int[] candidates, int index, int remainNum){
if(index >= 0 && remainNum >= 0){
if(remainNum == 0){
ArrayList<Integer> oneRes = new ArrayList<Integer>();
for(int i = comb.size()-1; i >= 0;i--){// reverse the order
oneRes.add(comb.get(i));
}
if(!res.contains(oneRes)) res.add(oneRes);
}
else{
comb.add(candidates[index]);
findCombOfSums(res,comb,candidates, index, remainNum - candidates[index]);
comb.remove(comb.size()-1);
findCombOfSums(res,comb,candidates, index - 1, remainNum);
}
}
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment