39. Combination Sum
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<>(); List<Integer> tmp = new ArrayList<>(); Arrays.sort(candidates); dfs(result, tmp, candidates, target, 0); return result; } private void dfs(List<List<Integer>> result, List<Integer> tmp, int[] candidates, int target, int index){ if(target == 0){ result.add(new ArrayList<>(tmp)); return; } if(candidates[index] > target){ return; // use return , instead of break?? why ?? } for(int i = index; i < candidates.length; i++){ tmp.add(candidates[i]); dfs(result, tmp, candidates, target - candidates[i], i); // tmp backtrack recovery tmp.remove(tmp.size() - 1); } } }
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
- All numbers (including
target) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[2,3,6,7],target =7, A solution set is: [ [7], [2,2,3] ]
Example 2:
Input: candidates = [2,3,5],target = 8, A solution set is: [ [2,2,2,2], [2,3,3], [3,5] ]
idea: in example 2, since we can use duplicates
for the first pos, we can use 2, 3, 5
if we use 2 for pos 1, pos 2 can be 2, 3, 5
if we use 3 for pos 1, pos 2 can be 3, 5
if we use 5 for pos 1, pos 2 can be 5
this ordering is for the deduplication purpose , we sort the array and use start index to prevent from looking back
no need to sort if the array is sorted
target - current number , until target = 0, we know we have a result
for pruning is when sum < nums[i], which is the current element
for base case is when sum == 0
time complexity in this example, there are at most 8/2 = 4 levels, and there are 3 options on each level at most,
so its 3 * 3 * 3 * 3
=========================
break vs continue vs return
break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.
return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.
break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.
The break statement results in the termination of the loop, it will come out of the loop and stops further iterations. The continue statement stops the current execution of the iteration and proceeds to the next iteration. The return statement takes you out of the method. It stops executing the method and returns from the method execution.
posted on 2018-07-18 08:04 猪猪🐷 阅读(102) 评论(0) 收藏 举报
浙公网安备 33010602011771号