Given a set of candidate numbers (C) (without duplicates) 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 CombinationSum_39 { List<List<Integer>> result = new ArrayList<List<Integer>>(); public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); for(int i = 0 ; i<candidates.length ; i++){ if(candidates[i] == target){ result.add(Arrays.asList(candidates[i])); }else{ List<Integer> temp = new ArrayList<Integer>(); temp.add(candidates[i]); combinationSum(candidates, i, target-candidates[i], temp); } } return result; } public void combinationSum(int[] candidates, int start, int target, List<Integer> currentResult){ for(int i = start ; i < candidates.length ; i++){ if(candidates[i] == target){ currentResult.add(candidates[i]); result.add(currentResult); return; } if(candidates[i] > target){ return; } if(candidates[i] < target){ List<Integer> temp = new ArrayList<Integer>(); temp.addAll(currentResult); temp.add(candidates[i]); combinationSum(candidates, i, target-candidates[i], temp); } } } }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~微信