Combination Sum

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.ide

Note:
spa

  • 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:
code

[
  [7],
  [2, 2, 3]
]
解題思路:深度遍歷,找出全部合格的數據。
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        work(target,0,candidates,res,new ArrayList<Integer>());
        return res;
    }
    //勝讀遍歷,找出合格的數據
    /*
     * target:表明目標數據
     * index:表明循環的其實位置,也就是查找合格數據的額起始位置
     * candidates 候選值數組
     * res:返回值
     * arrayList:保存一組合格數據的變量
     * */
    public void work(int target, int index, int[] candidates, List<List<Integer>> res, ArrayList<Integer> arrayList){
        //for循環,每次從index出發,由於數組已經排序,因此不會出現重複的數據
        //終止條件爲索引越界&&目標值要大於等於當前要檢查的候選值
        for(int i=index;i<candidates.length&&candidates[i]<=target;i++){
            /*
             * 若是target大於當前從candidate中提取的值時,則能夠將其加入到arrayList中,在進入深度的遍歷查找合格數據
             * 注意的是,當不管是查找成功仍是失敗的時候,都要將arrayList的最後一個數據彈出,一遍進行下一次的深度遍歷
             * */
            if(candidates[i]<target){
                arrayList.add(candidates[i]);
                work(target-candidates[i], i, candidates, res, arrayList);
                arrayList.remove(arrayList.size()-1);
            }
            /*
             * 若是target==當前提取的candidate中的值,則代表查找成功,將這一數組添加到res橫中
             * 而且彈出彈出arrayList中的最後一個數據進行下一次的遍歷
             * */
            else if(candidates[i]==target){
                arrayList.add(candidates[i]);
                res.add(new ArrayList<Integer>(arrayList));
                arrayList.remove(arrayList.size()-1);
            }
        }
    }
}
View Code
相關文章
相關標籤/搜索