1. 程式人生 > >Combination Sum II -- LeetCode

Combination Sum II -- LeetCode

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

                原題連結:  http://oj.leetcode.com/problems/combination-sum-ii/  

這道題跟Combination Sum

非常相似,不瞭解的朋友可以先看看,唯一的區別就是這個題目中單個元素用過就不可以重複使用了。乍一看好像區別比較大,但是其實實現上只需要一點點改動就可以完成了,就是遞迴的時候傳進去的index應該是當前元素的下一個。程式碼如下: 

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迴圈前做一次判斷,因為雖然一個元素不可以重複使用,但是如果這個元素重複出現是允許的,但是為了避免出現重複的結果集,我們只對於第一次得到這個數進行遞迴,接下來就跳過這個元素了,因為接下來的情況會在上一層的遞迴函式被考慮到,這樣就可以避免重複元素的出現。這個問題可能會覺得比較繞,大家仔細想想就明白了哈。

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述