From c0980197c4a556757de72829b58b4efb6e5ae470 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:37:31 +0900 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200077.=E7=BB=84=E5=90=88.md?= =?UTF-8?q?=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 3dfb5216..f31766e0 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -340,6 +340,33 @@ public: Java: +```java +class Solution { + List> result = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + public List> combine(int n, int k) { + combineHelper(n, k, 1); + return result; + } + + /** + * 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex + * @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。 + */ + private void combineHelper(int n, int k, int startIndex){ + //终止条件 + if (path.size() == k){ + result.add(new ArrayList<>(path)); + return; + } + for (int i = startIndex; i <= n - (k - path.size()) + 1; i++){ + path.add(i); + combineHelper(n, k, i + 1); + path.removeLast(); + } + } +} +``` Python: