Leetcode40. Combination Sum II
和39题一个系列,做法基本相同,只不过更改几个条件。
1 class Solution { 2 public List<List<Integer>> combinationSum2(int[] nums, int target) { 3 List<List<Integer>> ans = new ArrayList<>(); 4 Arrays.sort(nums); 5 backTracking(nums,target,ans,new ArrayList<>(),0); 6 return ans; 7 } 8 private void backTracking(int[] nums,int target,List<List<Integer>> ans,List<Integer> tempList,int start){ 9 if(target<0) return; 10 else if(target==0){ 11 ans.add(new ArrayList<>(tempList)); 12 return; 13 }else{ 14 for(int i=start;i<nums.length;i++){ 15 if(i>start&&nums[i]==nums[i-1]) continue; 16 //think with [1,1,1,2,2,3,5] target=6 and draw a tree with DFS methodology and you will understang the upper line 17 tempList.add(nums[i]); 18 backTracking(nums,target-nums[i],ans,tempList,i+1); 19 tempList.remove(tempList.size()-1); 20 } 21 } 22 } 23 }
25ms,19.53%.
最快思路时间复杂度上相当。
所以个人最优解即可。
关于i>start。
14行的for循环是用于每轮的递归进行不下去或者进行完了后往下一个值走的情况下的。也就是以每个子问题:将target减去templist里数的和得到新的target和当前剩下的数们这个子问题。以每个子问题的第一个元素开始往下循环。说的有点废话。还是看备注自己理一遍吧。

浙公网安备 33010602011771号