From e601c0c729a0deab40982e672d02618bda76ff88 Mon Sep 17 00:00:00 2001 From: AronJudge <2286381138@qq.com> Date: Sun, 4 Sep 2022 10:39:02 +0800 Subject: [PATCH] =?UTF-8?q?0216.=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8CIII?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加一种更简单的剪裁方式。 --- problems/0216.组合总和III.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 2c1bf717..50c0d746 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -260,6 +260,37 @@ class Solution { } } } + +// 上面剪枝 i <= 9 - (k - path.size()) + 1; 如果还是不清楚 +// 也可以改为 if (path.size() > k) return; 执行效率上是一样的 +class Solution { + LinkedList path = new LinkedList<>(); + List> ans = new ArrayList<>(); + public List> combinationSum3(int k, int n) { + build(k, n, 1, 0); + return ans; + } + + private void build(int k, int n, int startIndex, int sum) { + + if (sum > n) return; + + if (path.size() > k) return; + + if (sum == n && path.size() == k) { + ans.add(new ArrayList<>(path)); + return; + } + + for(int i = startIndex; i <= 9; i++) { + path.add(i); + sum += i; + build(k, n, i + 1, sum); + sum -= i; + path.removeLast(); + } + } +} ``` 其他方法