劍指 Offer II 081. 允許重復選擇元素的組合


comments: true
edit_url: https://github.com/doocs/leetcode/edit/main/lcof2/%E5%89%91%E6%8C%87%20Offer%20II%20081.%20%E5%85%81%E8%AE%B8%E9%87%8D%E5%A4%8D%E9%80%89%E6%8B%A9%E5%85%83%E7%B4%A0%E7%9A%84%E7%BB%84%E5%90%88/README.md

劍指 Offer II 081. 允許重復選擇元素的組合

題目描述

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

candidates?中的數字可以無限制重復被選取。如果至少一個所選數字數量不同,則兩種組合是唯一的。?

對于給定的輸入,保證和為?target 的唯一組合數少于 150 個。

?

示例?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]]

示例 3:

輸入: candidates = [2], target = 1
輸出: []

示例 4:

輸入: candidates = [1], target = 1
輸出: [[1]]

示例 5:

輸入: candidates = [1], target = 2
輸出: [[1,1]]

?

提示:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每個元素都是獨一無二的。
  • 1 <= target <= 500

?

注意:本題與主站 39?題相同:?https://leetcode.cn/problems/combination-sum/

解法

方法一

Python3
class Solution:def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:res=[]path=[]def dfs(i):s=sum(path)if s==target:res.append(path[:])returnif s > target: #如果沒有這個,會無限遞歸returnfor j in range(i,len(candidates)):path.append(candidates[j])dfs(j)path.pop()dfs(0)return res
Java
class Solution {private List<List<Integer>> ans;private int target;private int[] candidates;public List<List<Integer>> combinationSum(int[] candidates, int target) {ans = new ArrayList<>();this.target = target;this.candidates = candidates;dfs(0, 0, new ArrayList<>());return ans;}private void dfs(int s, int u, List<Integer> t) {if (s == target) {ans.add(new ArrayList<>(t));return;}if (s > target) {return;}for (int i = u; i < candidates.length; ++i) {int c = candidates[i];t.add(c);dfs(s + c, i, t);t.remove(t.size() - 1);}}
}
C++
class Solution {
public:vector<vector<int>> ans;vector<int> candidates;int target;vector<vector<int>> combinationSum(vector<int>& candidates, int target) {this->candidates = candidates;this->target = target;vector<int> t;dfs(0, 0, t);return ans;}void dfs(int s, int u, vector<int>& t) {if (s == target) {ans.push_back(t);return;}if (s > target) return;for (int i = u; i < candidates.size(); ++i) {int c = candidates[i];t.push_back(c);dfs(s + c, i, t);t.pop_back();}}
};
Go
func combinationSum(candidates []int, target int) [][]int {var ans [][]intvar dfs func(s, u int, t []int)dfs = func(s, u int, t []int) {if s == target {ans = append(ans, append([]int(nil), t...))return}if s > target {return}for i := u; i < len(candidates); i++ {c := candidates[i]t = append(t, c)dfs(s+c, i, t)t = t[:len(t)-1]}}var t []intdfs(0, 0, t)return ans
}
C#
using System;
using System.Collections.Generic;
using System.Linq;public class Solution
{public IList<IList<int>> CombinationSum(int[] candidates, int target){Array.Sort(candidates);candidates = candidates.Distinct().ToArray();var paths = new List<int>[target + 1];paths[0] = new List<int>();foreach (var c in candidates){for (var j = c; j <= target; ++j){if (paths[j - c] != null){if (paths[j] == null){paths[j] = new List<int>();}paths[j].Add(c);}}}var results = new List<IList<int>>();if (paths[target] != null) GenerateResults(results, new Stack<int>(), paths, target, paths[target].Count - 1);return results;}private void GenerateResults(IList<IList<int>> results, Stack<int> result, List<int>[] paths, int remaining,int maxIndex){if (remaining == 0){results.Add(new List<int>(result));return;}for (var i = maxIndex; i >= 0; --i){var value = paths[remaining][i];result.Push(value);var nextMaxIndex = paths[remaining - value].BinarySearch(value);if (nextMaxIndex < 0){nextMaxIndex = ~nextMaxIndex - 1;}GenerateResults(results, result, paths, remaining - value, nextMaxIndex);result.Pop();}}
}
Swift
class Solution {private var ans: [[Int]] = []private var target: Int = 0private var candidates: [Int] = []func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {self.ans = []self.target = targetself.candidates = candidatesdfs(0, 0, [])return ans}private func dfs(_ sum: Int, _ index: Int, _ current: [Int]) {if sum == target {ans.append(current)return}if sum > target {return}for i in index..<candidates.count {let candidate = candidates[i]dfs(sum + candidate, i, current + [candidate])}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/897968.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/897968.shtml
英文地址,請注明出處:http://en.pswp.cn/news/897968.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Webpack 前端性能優化全攻略

文章目錄 1. 性能優化全景圖1.1 優化維度概覽1.2 優化效果指標 2. 構建速度優化2.1 緩存策略2.2 并行處理2.3 減少構建范圍 3. 輸出質量優化3.1 代碼分割3.2 Tree Shaking3.3 壓縮優化 4. 運行時性能優化4.1 懶加載4.2 預加載4.3 資源優化 5. 高級優化策略5.1 持久化緩存5.2 模…

虛擬電商-數據庫分庫分表(二)

本文章介紹&#xff1a;使用Sharding-JDBC實現數據庫分庫分表&#xff0c;數據庫分片策略&#xff0c;實現數據庫按月分表 一、Sharding-JDBC使用 1.1.準備環境 步驟一&#xff1a;分庫分表sql腳本導入 創建了兩個數據庫&#xff1a;chongba_schedule0 和chongba_schedule1…

向量數據庫對比以及Chroma操作

一、向量數據庫與傳統類型數據庫 向量數據庫&#xff08;Vector Storage Engine&#xff09;與傳統類型的數據庫如關系型數據庫&#xff08;MySQL&#xff09;、文檔型數據庫&#xff08;MongoDB&#xff09;、鍵值存儲&#xff08;Redis&#xff09;、全文搜索引擎&#xff0…

python列表基礎知識

列表 創建列表 1.列表的定義&#xff1a;可變的&#xff0c;有序的數據結構&#xff0c;可以隨時添加或者刪除其中的元素 2.基本語法&#xff1a;字面量【元素1&#xff0c;元素2&#xff0c;元素3】使用[]創建列表 定義變量&#xff1a;變量名稱【元素1&#xff0c;元素2&…

Node.js 的模塊作用域和 module 對象詳細介紹

目錄 代碼示例 1. 創建模塊文件 module-demo.js 2. 導入模塊并使用 module-demo.js 運行結果 總結 在 Node.js 中&#xff0c;每個文件都是一個獨立的模塊&#xff0c;具有自己的作用域。與瀏覽器 JavaScript 代碼不同&#xff0c;Node.js 采用模塊作用域&#xff0c;這意味…

美暢物聯丨WebRTC 技術詳解:構建實時通信的數字橋梁

在互聯網技術飛速發展的今天&#xff0c;實時通信已成為數字生活的核心需求。WebRTC作為一個開源項目&#xff0c;憑借卓越的技術實力與創新理念&#xff0c;為網頁和移動應用帶來了顛覆性的實時通信能力。它突破了傳統通信方式的限制&#xff0c;實現了音頻、視頻和數據在用戶…

excel中兩個表格的合并

使用函數&#xff1a; VLOOKUP函數 如果涉及在excel中兩個工作表之間進行配對合并&#xff0c;則&#xff1a; VLOOKUP(C1,工作表名字!A:B,2,0) 參考&#xff1a; excel表格中vlookup函數的使用方法步驟https://haokan.baidu.com/v?pdwisenatural&vid132733503560775…

單引號與雙引號在不同編程語言中的使用與支持

在編程語言中&#xff0c;單引號和雙引號是常見的符號&#xff0c;它們通常用來表示字符和字符串。然而&#xff0c;如何使用這兩種符號在不同的編程語言中有所不同&#xff0c;甚至有一些語言并不區分單引號和雙引號的用途。本文將詳細介紹不同編程語言中單引號與雙引號的支持…

怎么鑒別金媒v10.51和v10.5的區別!單單從CRM上區分!

2.怎么鑒別程序是10.5還是10.51 &#xff1f;* 作為商業用戶&#xff0c;升級完全沒有這個擔心&#xff0c;但是這次升級從全局來看清晰度不是很高&#xff0c;不像10.5的升級后臺UI都變化了&#xff01;你說有漏洞但是我沒遇到過 所以我也不知道升級了啥只能看版本數字是無法區…

python腳本實現服務器內存和cpu使用監控,并記錄日志,可以設置閾值和采樣頻率

Python 腳本&#xff0c;實現以下功能&#xff1a; 按日期自動生成日志文件&#xff08;例如 cpu_mem_20231001.csv&#xff09;當 CPU 或內存超過閾值時觸發記錄獨立記錄報警事件&#xff08;保存到 alert.log&#xff09;支持自定義閾值和監控間隔 腳本代碼 import psutil …

【Oracle】19c數據庫控制文件多路徑配置

一、關閉數據庫&#xff08;2個節點實例都要關閉&#xff09; srvctl stop database -d ora19c 二、多路徑控制文件 打開其中一個節點到nomount狀態 sqlplus / as sysdba startup nomount; [oracleora19c1:/home/oracle]$ rman target / RMAN> restore controlfile to…

大模型訓練全流程深度解析

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到網站。https://www.captainbed.cn/north 文章目錄 1. 大模型訓練概覽1.1 訓練流程總覽1.2 關鍵技術指標 2. 數據準備2.1 數據收集與清洗2.2 數據…

【Linux】進程(1)進程概念和進程狀態

&#x1f31f;&#x1f31f;作者主頁&#xff1a;ephemerals__ &#x1f31f;&#x1f31f;所屬專欄&#xff1a;Linux 目錄 前言 一、什么是進程 二、task_struct的內容 三、Linux下進程基本操作 四、父進程和子進程 1. 用fork函數創建子進程 五、進程狀態 1. 三種重…

lws-minimal-ws-server前端分析

index.html index.html是前端入口 <html><head><meta charsetutf-8 http-equiv"Content-Language" content"en"/><!-- 引入js --><script src"/example.js"></script></head><body><img s…

L1-7 統一命名規范(java)

你所在的公司剛剛招收了幾位程序員&#xff0c;然而這些程序員之前在不同的公司工作&#xff0c;所以他們習慣的變量命名規范可能存在差異&#xff0c;需要讓他們都習慣公司要求的命名規范&#xff0c;然而這樣可能會降低他們的工作效率。 你的上司找到了你&#xff0c;希望你…

Flexus應用服務器L實例、X實例以及ECS(彈性計算服務)之間的區別及其適用場景

為了更好地理解Flexus應用服務器L實例、X實例以及ECS&#xff08;彈性計算服務&#xff09;之間的區別及其適用場景&#xff0c;下面我將通過具體的例子來說明每種類型的使用情況。 1. Flexus L實例 特點: 針對高并發和負載均衡進行了優化。它可能包括更快的網絡接口、更高效…

WebRTC中音視頻服務質量QoS之RTT衡量網絡往返時延的加權平均RTT計算機制?詳解

WebRTC中音視頻服務質量QoS之RTT衡量網絡往返時延加權平均RTT計算機制?的詳解 WebRTC中音視頻服務質量QoS之RTT衡量網絡往返時延加權平均RTT計算機制?的詳解 WebRTC中音視頻服務質量QoS之RTT衡量網絡往返時延加權平均RTT計算機制?的詳解前言一、 RTT 網絡往返時延的原理?1、…

odbus TCP轉Modbus RTU網關快速配置案例

Modbus TCP 轉Modbus RTU網關快速配置案例 在工業自動化領域&#xff0c;Modbus 協議以其簡潔和高效而著稱&#xff0c;成為眾多設備通信的首選。 隨著技術的發展和應用場景的變化&#xff0c;Modbus 協議也發展出了不同的版本&#xff0c;其中 Modbus TCP 和 Modbus RTU 是兩種…

《高效遷移學習:Keras與EfficientNet花卉分類項目全解析》

從零到精通的遷移學習實戰指南&#xff1a;以Keras和EfficientNet為例 一、為什么我們需要遷移學習&#xff1f; 1.1 人類的學習智慧 想象一下&#xff1a;如果一個已經會彈鋼琴的人學習吉他&#xff0c;會比完全不懂音樂的人快得多。因為TA已經掌握了樂理知識、節奏感和手指…

WSL2 Ubuntu安裝GCC不同版本

WSL2 Ubuntu安裝GCC不同版本 介紹安裝gcc 7.1方法 1&#xff1a;通過源碼編譯安裝 GCC 7.1步驟 1&#xff1a;安裝編譯依賴步驟 2&#xff1a;下載 GCC 7.1 源碼步驟 3&#xff1a;配置和編譯步驟 4&#xff1a;配置環境變量步驟 5&#xff1a;驗證安裝 方法 2&#xff1a;通過…