[刷题]Combination Sum II

[LintCode]Combination Sum II

public class Solution {
    /**
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        // 2015-07-09
        // num中可以含重复元素,每个元素只能使用一次
        // 解集中不可以含相同的解
        List<List<Integer>> rst = new ArrayList<List<Integer>>();
        if (num == null || num.length == 0) {
            return rst;
        }
        Arrays.sort(num);
        ArrayList<Integer> list = new ArrayList<>();
        helper(rst, list, num, target, 0);
        return rst;
    }
    
    private void helper(List<List<Integer>> rst, ArrayList<Integer> list, int[] num, int t, int pos) {
        if (t == 0) {
            rst.add(new ArrayList<Integer>(list));
            return;
        }
        for (int i = pos; i < num.length; i++) {
            if (t - num[i] < 0) {
                break;
            }
            if (i != pos && num[i] == num[i - 1]) { // 关键:注意是pos
                continue;
            }
            list.add(num[i]);
            helper(rst, list, num, t - num[i], i + 1);
            list.remove(list.size() - 1);
        }
        return;
    }
}


阅读更多
个人分类: search
上一篇[刷题]Combination Sum
下一篇[刷题]Word Ladder
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭