自学内容网 自学内容网

LeetCode 40-组合总数Ⅱ

题目链接:LeetCode40

欢迎留言交流,每天都会回消息。

class Solution {
    List<List<Integer>> rs = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0, 0);
        return rs;
    }

    void backTracking(int[] candidates, int target, int sum, int startIdx) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            rs.add(new ArrayList<Integer>(path));
            return;
        }

        for (int i = startIdx; i < candidates.length; i++) {
            if (i > startIdx && candidates[i] == candidates[i - 1]) {
                continue;
            }
            sum += candidates[i];
            path.add(candidates[i]);
            backTracking(candidates, target, sum, i + 1);
            path.removeLast();
            sum -= candidates[i];
        }
    }
}

原文地址:https://blog.csdn.net/qq_45801839/article/details/143695983

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!