日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Leetcode][第40题][JAVA][数组总和2][回溯][剪枝]

發(fā)布時間:2023/12/10 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Leetcode][第40题][JAVA][数组总和2][回溯][剪枝] 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

【問題描述】[中等]

【解答思路】


1. 減法
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.List;public class Solution {public List<List<Integer>> combinationSum2(int[] candidates, int target) {int len = candidates.length;List<List<Integer>> res = new ArrayList<>();if (len == 0) {return res;}// 關(guān)鍵步驟Arrays.sort(candidates);Deque<Integer> path = new ArrayDeque<>(len);dfs(candidates, len, 0, target, path, res);return res;}/*** @param candidates 候選數(shù)組* @param len 冗余變量* @param begin 從候選數(shù)組的 begin 位置開始搜索* @param target 表示剩余,這個值一開始等于 target,基于題目中說明的"所有數(shù)字(包括目標數(shù))都是正整數(shù)"這個條件* @param path 從根結(jié)點到葉子結(jié)點的路徑* @param res*/private void dfs(int[] candidates, int len, int begin, int target, Deque<Integer> path, List<List<Integer>> res) {if (target == 0) {res.add(new ArrayList<>(path));return;}for (int i = begin; i < len; i++) {// 大剪枝if (target - candidates[i] < 0) {break;}// 小剪枝if (i > begin && candidates[i] == candidates[i - 1]) {continue;}path.addLast(candidates[i]);// 因為元素不可以重復(fù)使用,這里遞歸傳遞下去的是 i + 1 而不是 idfs(candidates, len, i + 1, target - candidates[i], path, res);path.removeLast();}}public static void main(String[] args) {int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5};int target = 8;Solution solution = new Solution();List<List<Integer>> res = solution.combinationSum2(candidates, target);System.out.println("輸出 => " + res);} }
2. 加法
class Solution {public List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {int len = candidates.length;boolean[] used = new boolean[len];Arrays.sort(candidates);dfs(candidates,target,new ArrayDeque<Integer>(),0,0);return res;}public void dfs(int[] cand,int target,Deque<Integer> temp,int sum,int index){if(sum>target) return;if(sum==target){res.add(new ArrayList<>(temp));return;}for(int i=index;i<cand.length;++i){if (i > index && cand[i] == cand[i - 1]) {continue;}temp.addLast(cand[i]);dfs(cand,target,temp,sum+cand[i],i+1);temp.removeLast();}} }

【總結(jié)】

1. 剪枝說明
2.回溯算法相關(guān)題目

[Leedcode][JAVA][第46題][全排列][回溯算法]
[Leetcode][第81題][JAVA][N皇后問題][回溯算法]
[Leetcode][第60題][JAVA][第k個排列][回溯][DFS][剪枝]
[Leetcode][第39題][JAVA][組合總和][回溯][dfs][剪枝]

轉(zhuǎn)載鏈接:https://leetcode-cn.com/problems/combination-sum-ii/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-m-3/

總結(jié)

以上是生活随笔為你收集整理的[Leetcode][第40题][JAVA][数组总和2][回溯][剪枝]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。