日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

LeetCode 78. 子集

發布時間:2025/6/15 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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. 子集的全部內容,希望文章能夠幫你解決所遇到的問題。

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