Skip to main content

🟡 剑指 Offer II 081. 允许重复选择元素的组合

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

class Solution {    private int[] candidates;    private int target;    private List<List<Integer>> ans = new ArrayList<>();    private List<Integer> res = new ArrayList<>();    private int resSum = 0;
    private void dfs() {      for (int cand : this.candidates) {        // 防止重复        if (this.res.size() > 0 && cand < this.res.get(this.res.size() - 1)) {          continue;        }        if (resSum + cand <= this.target) {          this.res.add(cand);          resSum += cand;          if (resSum == this.target) {            this.ans.add(new ArrayList(this.res));          } else {            dfs();          }          this.res.remove(this.res.size() - 1);          resSum -= cand;        }      }    }
    public List<List<Integer>> combinationSum(int[] candidates, int target) {      this.candidates = candidates;      this.target = target;      this.dfs();
      return this.ans;    }}