leetcode:Combination Sum(I,II)

原題:
Given a set of candidate numbers (C) 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.

Note:

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:

[ [7], [2, 2, 3] ]

升級:
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 target 8,
A solution set is:

[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]

回溯法:

Combination Sum

public class Solution {

        public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        backtrace(result,new ArrayList<Integer>(),candidates,target,0);
        return result;
    }
    private static void backtrace(List<List<Integer>> list, ArrayList<Integer> tempList, int [] nums, int remain, int start){
        if(remain < 0) return;
        else if(remain == 0) list.add(new ArrayList<>(tempList));
        else{ 
            for(int i = start; i < nums.length; i++){
                tempList.add(nums[i]);
                backtrace(list, tempList, nums, remain - nums[i], i); //從i開始,集合可以含有重複元素
                tempList.remove(tempList.size() - 1);//最後一個元素放入元素使得remain<0,故要排除最後一個元素,按原路回退一步
            }
        }
    }
}

Combination Sum(II)

public class Solution {
    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        backtrack(result,new ArrayList<Integer>(),candidates,target,0);
        return result; 
    }
    private static void backtrack(List<List<Integer>> result,ArrayList<Integer> tempList, int[] candidates, int remain, int idx) {
        if(remain<0) return ;
        else if(remain==0) result.add(new ArrayList<>(tempList));
        else{
            for (int i = idx; i < candidates.length; i++) {
                if(i > idx && candidates[i] == candidates[i-1]) continue;//跳過重複元素
                tempList.add(candidates[i]);
                backtrack(result, tempList, candidates, remain-candidates[i], i+1);不能從自身元素開始搜索
                tempList.remove(tempList.size()-1);
            }
        }
    } 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章