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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 78. 子集

發布時間:2025/6/15 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 78. 子集 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

給定一組不含重復元素的整數數組?nums,返回該數組所有可能的子集(冪集)。

說明:解集不能包含重復的子集。

示例:

輸入: nums = [1,2,3] 輸出: [[3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[] ]來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/subsets

?

方法一: 暴力法(擴展發) 效率比較慢

?

class Solution {public List<List<Integer>> subsets(int[] nums) {List<List<Integer>> resultList = new ArrayList<List<Integer>>();resultList.add(new ArrayList());for(int num : nums){System.out.println(num);int size = resultList.size();for(int i=0; i<size; i++){ArrayList cur = new ArrayList(resultList.get(i));cur.add(num);resultList.add(cur);}}System.out.println(resultList);return resultList;} }

?

?

?

方法二:回溯法

import java.util.ArrayList; import java.util.List;public class SubSets {public static void main(String[] args) {int[] nums = { 1,2,3};List<List<Integer>> res = new ArrayList<List<Integer>>();for(int i=0; i<nums.length+1; i++){backtracking(nums, i/*表示第i層*/ ,0/*每一層都從下標0開始遍歷*/,res,new ArrayList()/*保存每一層的結果*/);}System.out.println(res);}/*** len: 層數* startIndex: 從數組哪個位置開始* res:最終結果* cur:保存每一層的結果*/ private static void backtracking(int[] nums, int len, int startIndex, List<List<Integer>> res, List<Integer> cur){if(cur.size() == len){// 當前層len 是否等于 當前層的結果list的長度res.add(new ArrayList(cur));return;}for(int i=startIndex; i<nums.length; i++){cur.add(nums[i]);backtracking(nums,len,i+1,res,cur);cur.remove(cur.size()-1);}}}

?

方法三:深度優先dfs算法

import java.util.ArrayList; import java.util.List;public class Subsets {public static void main(String[] args) {int[] nums = {1, 2, 3};ArrayList res = new ArrayList();dfs(nums, 0, res, new ArrayList());System.out.println(res);}private static void dfs(int[] nums, int startIndex, List<List<Integer>> res, List<Integer> cur){res.add(new ArrayList<>(cur));for(int i=startIndex; i<nums.length; i++){cur.add(nums[i]);dfs(nums,i+1,res,cur);cur.remove(cur.size()-1);}} }

?

?

?

總結

以上是生活随笔為你收集整理的LeetCode 78. 子集的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。