LeetCode-Combination Sum
Problem
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]*
Ideas
Since each element can be used multiple times, for a combination (taking [2, 2, 3] as an example)
1. Select 2 first, then the target has 5 left. For the second time, you can select 2, 3, but not 6, because 6 has exceeded the target. Iteration repeats this process. You can select [2, 2, 3 ].
2. repeat this process again. Select 3 for the first time, and then 4 for the target. You cannot select the remaining one.
Code
public class Solution { public List
> combinationSum(int[] candidates, int target) { List
> result = new ArrayList
>(); if(candidates == null || target < 0){ return result; } Arrays.sort(candidates); helper(candidates, target, result , new ArrayList
() , 0); return result; } private void helper(int[] candidates, int target, List
> result, List
solution , int begin){ if(target == 0){ result.add(new ArrayList
(solution)); return; } for(int i = begin ; i < candidates.length && target >= candidates[i] ; i++){ solution.add(candidates[i]); helper(candidates, target-candidates[i] , result , solution , i); solution.remove(solution.size() - 1); } }}
Parsing the remove Method of the appended ArrayList
The remove Method of ArrayList has two overloaded versions. They are
public E remove(int);public boolean remove(Object);
The first method is to delete the element at the specified position, and the second method is to delete the first element that appears with the equal parameter. The problem arises. If the List is defined:
List
mList = new ArrayList
();
Does it delete the element at the specified position or the number equal to the parameter?
This depends on the reload rule:
Parameter type widening (type compatibility)> automatic packing> Variable Length Parameter
Therefore, if the element in the mList has[1,2,3,4,5], We call the method:
mList.remove(1)Result changed[1,3,4,5].
Call againmList.remove(new Integer(1))The elements in the mList are eventually[3,4,5].