40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

For example, given candidate set[10, 1, 2, 7, 6, 1, 5]
and target8
,A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]

public class Solution {
    private List<List<Integer>> ans = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates.length==0||target<=0)
           return null;
        List<Integer> res = new ArrayList<Integer>();
        Arrays.sort(candidates);
        fun(candidates,0,target,res);
        return ans;
          
    }
    private void fun(int[] candidates,int start,int target,List<Integer> curr)
    {
        if(target == 0)
        {  
            List<Integer> list = new ArrayList<Integer>(curr);//若沒有這一句,直接用ans.add(curr)的話,curr每次是變化的。
            ans.add(list);
        }
        else
        {
            for(int i = start;i<candidates.length;i++)
            {
                if(i!=start&&candidates[i]==candidates[i-1])  //去除重復(fù)
                    continue;
                if(target>=candidates[i])
                {
                    curr.add(candidates[i]);
                    fun(candidates,i+1,target-candidates[i],curr); //下次遞歸不能從當(dāng)前位置開始
                    curr.remove(curr.size()-1);
                }
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,931評(píng)論 0 33
  • SOS 新進(jìn)外貿(mào)業(yè)務(wù)員的憂慮 應(yīng)屆畢業(yè)生 在綜合了各方面的條件后選擇了目前這一家公司 現(xiàn)在有一點(diǎn)是焦慮的 公司是規(guī)...
    雕雞閱讀 247評(píng)論 0 0
  • 向來仰慕東坡先生,大才!不僅看的通現(xiàn)世更明的懂人心。 食無肉的結(jié)果是瘦,居無竹的結(jié)果是俗!瘦可以補(bǔ),俗就無可救藥了...
    野花2016閱讀 297評(píng)論 0 0

友情鏈接更多精彩內(nèi)容