39. 組合總和

  • 2019 年 10 月 10 日
  • 筆記

題目描述

給定一個無重複元素的數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。

candidates 中的數字可以無限制重複被選取。

說明:

所有數字(包括 target)都是正整數。解集不能包含重複的組合。 示例 1:

輸入: candidates = [2,3,6,7], target = 7,  所求解集為:  [    [7],    [2,2,3]  ]

示例 2:

輸入: candidates = [2,3,5], target = 8,  所求解集為:  [    [2,2,2,2],    [2,3,3],    [3,5]  ]

來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/combination-sum 著作權歸領扣網路所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路

這道題目是求集合,並不是 求極值,因此動態規劃不是特別切合,因此我們需要考慮別的方法。

這種題目其實有一個通用的解法,就是回溯法。網上也有大神給出了這種回溯法解題的 通用寫法,這裡的所有的解法使用通用方法解答。除了這道題目還有很多其他題目可以用這種通用解法,具體的題目見後方相關題目部分。

我們先來看下通用解法的解題思路,我畫了一張圖:

通用寫法的具體程式碼見下方程式碼區。

關鍵點解析

  • 回溯法
  • backtrack 解題公式

程式碼

/*   * @lc app=leetcode id=39 lang=javascript   *   * [39] Combination Sum   *   * https://leetcode.com/problems/combination-sum/description/   *   * algorithms   * Medium (46.89%)   * Total Accepted:    326.7K   * Total Submissions: 684.2K   * Testcase Example:  '[2,3,6,7]n7'   *   * Given a set of candidate numbers (candidates) (without duplicates) and a   * target number (target), find all unique combinations in candidates where the   * candidate numbers sums to target.   *   * The same repeated number may be chosen from candidates unlimited number of   * times.   *   * Note:   *   *   * All numbers (including target) will be positive integers.   * The solution set must not contain duplicate combinations.   *   *   * Example 1:   *   *   * Input: candidates = [2,3,6,7], target = 7,   * A solution set is:   * [   * ⁠ [7],   * ⁠ [2,2,3]   * ]   *   *   * Example 2:   *   *   * Input: candidates = [2,3,5], target = 8,   * A solution set is:   * [   * [2,2,2,2],   * [2,3,3],   * [3,5]   * ]   *   */    function backtrack(list, tempList, nums, remain, start) {    if (remain < 0) return;    else if (remain === 0) return list.push([...tempList]);    for (let i = start; i < nums.length; i++) {      tempList.push(nums[i]);      backtrack(list, tempList, nums, remain - nums[i], i); // 數字可以重複使用, i + 1代表不可以重複利用      tempList.pop();    }  }  /**   * @param {number[]} candidates   * @param {number} target   * @return {number[][]}   */  var combinationSum = function(candidates, target) {    const list = [];    backtrack(list, [], candidates.sort((a, b) => a - b), target, 0);    return list;  };

相關題目

  • 40.combination-sum-ii
  • 46.permutations
  • 47.permutations-ii
  • 78.subsets
  • 90.subsets-ii
  • 113.path-sum-ii
  • 131.palindrome-partitioning