2014年10月16日星期四

[Leetcode] Combination Sum


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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 
递归求解,每次加进去一个数字,然后在以该数字开始的数组上递归求解,注意去除重复的元素就可以。这道题和之前写的Combination Sum II 应该是一样的写法,不过我之前那到题写的有些复杂,写成Subset那道题的递归写法了。
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(candidates);
        dfs(candidates, target, 0, list, result);
        return result;
    }
    
    private void dfs(int[] num, int current, int beg, List<Integer> list, List<List<Integer>> result) {
        if(current < 0) return ;
        else if(current == 0) {
            result.add(new ArrayList<Integer>(list));
        }
        else {
            for(int i = beg; i < num.length; i++) {
                if(i > beg && num[i] == num[i-1]) continue;
                list.add(num[i]);
                dfs(num, current-num[i], i, list, result);
                list.remove(list.size() - 1);
            }
        }
    }

没有评论:

发表评论