2016年7月21日星期四

[LeetCode] #40 Combination Sum II

Time complexity: O(2^n)

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return result;
        }
        Arrays.sort(candidates);
        helper(result, new ArrayList<Integer>(), 0, candidates, target, 0);
        return result;
    }
    
    private void helper(List<List<Integer>> result, List<Integer> path, int sum, int[] candidates, int target, int start) {
        if (sum == target) {
            result.add(new ArrayList<Integer>(path));
            return;
        }
        
        for (int i = start; i < candidates.length; i++) {
            if (i > 0 && i != start && candidates[i] == candidates[i - 1]) {
                continue;
            }
            if (sum + candidates[i] > target) {
                break;
            } else {
                path.add(candidates[i]);
                helper(result, path, sum + candidates[i], candidates, target, i + 1);
                path.remove(path.size() - 1);
            }
        }
    }
}


没有评论:

发表评论