Leetcode 216. Combination Sum II

作者: ShutLove | 来源:发表于2017-11-27 10:51 被阅读12次

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]

思路:
深度优先搜索,即从1开始穷举可能的组合,每穷举一个数字就把总和n减去这个数字,并把k减1,穷举过的数字用布尔类型的数组标记,但是如果尝试的组合最后失败,需要回溯把标记去除。
另外需去除重复组合,因此每次不需要再尝试前面的数字。
另外如果当前开始搜索的数字已经大于n,也不必进行尝试。

public List<List<Integer>> combinationSum3(int k, int n) {
    List<List<Integer>> res = new ArrayList<>();
    if (k > 9) {
        return res;
    }

    //use flag to mark used number
    boolean[] flag = new boolean[10];
    //use list to store the current combination
    List<Integer> list = new ArrayList<>();
    //use dfs to find the res
    dfs(n, k, flag, list, res, 1);

    return res;
}

private void dfs(int n, int k, boolean[] flag, List<Integer> list, List<List<Integer>> res, int start) {
    if (n == 0 && k == 0) {
        res.add(new ArrayList<>(list));
        return;
    }
    //start大于n,肯定没有合适组合,剪枝
    if (start > n) {
        return;
    }

    //避免重复组合,从start开始,前面的不必尝试,
    for (int i = start; i <= 9; i++) {
        if (flag[i]) {
            continue;
        }
        flag[i] = true;
        list.add(i);
        dfs(n - i, k - 1, flag, list, res, i + 1);
        list.remove(list.size() - 1);
        flag[i] = false;
    }
}

相关文章

网友评论

    本文标题:Leetcode 216. Combination Sum II

    本文链接:https://www.haomeiwen.com/subject/itprbxtx.html