From 988211e8892fdba5c9c2b15a0489bd7734af946e Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 21:00:14 +0800 Subject: [PATCH] =?UTF-8?q?Update=200039.=E7=BB=84=E5=90=88=E6=80=BB?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index f983a994..ab118ee0 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -236,7 +236,39 @@ public: Java: +```Java +class Solution { + List> lists = new ArrayList<>(); + Deque deque = new LinkedList<>(); + public List> combinationSum3(int k, int n) { + int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; + backTracking(arr, n, k, 0); + return lists; + } + + public void backTracking(int[] arr, int n, int k, int startIndex) { + //如果 n 小于0,没必要继续本次递归,已经不符合要求了 + if (n < 0) { + return; + } + if (deque.size() == k) { + if (n == 0) { + lists.add(new ArrayList(deque)); + } + return; + } + for (int i = startIndex; i < arr.length - (k - deque.size()) + 1; i++) { + deque.push(arr[i]); + //减去当前元素 + n -= arr[i]; + backTracking(arr, n, k, i + 1); + //恢复n + n += deque.pop(); + } + } +} +``` Python: