Combination Sum II -- LeetCode
阿新 • • 發佈:2018-11-16
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
原題連結: http://oj.leetcode.com/problems/combination-sum-ii/這道題跟Combination Sum
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (num == null || num.length==0) return res; Arrays.sort(num); helper(num,0,target,new ArrayList<Integer>(),res); return res;}private void helper(int[] num, int start, int target, ArrayList<Integer> item,ArrayList<ArrayList<Integer>> res) { if(target == 0) { res.add(new ArrayList<Integer>(item)); return; } if(target<0 || start>=num.length) return; for(int i=start;i<num.length;i++) { if(i>start && num[i]==num[i-1]) continue; item.add(num[i]); helper(num,i+1,target-num[i],item,res); item.remove(item.size()-1); }}
在這裡我們還是需要在每一次for迴圈前做一次判斷,因為雖然一個元素不可以重複使用,但是如果這個元素重複出現是允許的,但是為了避免出現重複的結果集,我們只對於第一次得到這個數進行遞迴,接下來就跳過這個元素了,因為接下來的情況會在上一層的遞迴函式被考慮到,這樣就可以避免重複元素的出現。這個問題可能會覺得比較繞,大家仔細想想就明白了哈。