39. 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.
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]
]

Solution1:Backtracking(DFS)

总结见:http://www.jianshu.com/p/883fdda93a66
思路:回溯法,类似深度优先进行组合,cur_result数组保持用当前尝试的结果,并按照深度优先次序依次将组合结果加入到result_list中,因为可以重复选择,start_next 仍= i, DFS到底后 step back (通过remove 当前cur_result的最后一位),换下一个尝试组合,后继续DFS重复此过程,实现上采用递归方式。
排序后可以部分剪枝,提前返回结果 加速。
回溯顺序:
输入[1, 2, 3]
[1, 1, 1] [1, 1, 2] [1, 1, 3] [1, 2, 2] [1, 2, 3] [1, 3, 3]
[2, 2, 2] [2, 2, 3] ...

Time Complexity: O((target_test_time) ^ N) since there could be a 重复情况
Space Complexity(不算result的话): O(2n) : n是递归缓存的cur_result + n是缓存了n层的普通变量O(1) ? (Not Sure)

Solution1 Code:

class Solution {
    public List> combinationSum(int[] candidates, int target) {
        List> result = new ArrayList<>();
        List cur_res = new ArrayList<>();
        Arrays.sort(candidates); //for possible early stop
        backtrack(candidates, 0, target, cur_res, result);
        return result;
    }

    private void backtrack(int[] nums, int start, int remain, List cur_res, List> result) {
        if(remain < 0) // early stop
            return;
        else if(remain == 0)
            result.add(new ArrayList<>(cur_res));
        else {
            for(int i = start; i < nums.length; i++) {
                cur_res.add(nums[i]);
                backtrack(nums, i, remain - nums[i], cur_res, result);
                cur_res.remove(cur_res.size() - 1);
            }
        }
    }
}

Solution1.Round1 Code:

class Solution {
    public List> combinationSum(int[] candidates, int target) {
        
        List> result = new ArrayList<>();
        if(candidates == null || candidates.length == 0) {
            return result;
        }
        List cur_res = new ArrayList<>();
        
        // Arrays.sort(candidates);
        backtrack(candidates, 0, 0, cur_res, result, target);
        return result;
        
    }
    
            
    private void backtrack(int[] candidates, int start, int cur_sum, List cur_res, List> result, int target) {
        if(cur_sum == target) {
            result.add(new ArrayList<>(cur_res));
            return;
        }
        else if(cur_sum > target) {
            return;
        }

        for(int i = start; i < candidates.length; i++) {
            cur_res.add(candidates[i]);
            backtrack(candidates, i, cur_sum + candidates[i], cur_res, result, target);
            cur_res.remove(cur_res.size() - 1);
        }
    }
}

你可能感兴趣的:(39. Combination Sum)