LeetCode78

題目鏈接https://leetcode-cn.com/problems/subsets/submissions/

題目:

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

說(shuō)明:解集不能包含重復(fù)的子集。

示例:

輸入:nums = [1,2,3]輸出:[? [3],? [1],? [2],? [1,2,3],? [1,3],? [2,3],? [1,2],? []

//方法1:二進(jìn)制法

class Solution {


? ? public List<List<Integer>> subsets(int[] nums) {

? ? ? ? int all_set = 1 << nums.length;


? ? ? ? ArrayList<List<Integer>> result = new ArrayList<>();


? ? ? ? for(int i = 0; i < all_set; i++){


? ? ? ? ? ? List<Integer> tmp = new ArrayList<Integer>();


? ? ? ? ? ? for(int j = 0; j < nums.length; j++){

? ? ? ? ? ? ? ? if(((i >> j) & 1) != 0){

? ? ? ? ? ? ? ? ? ? tmp.add(nums[j]);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? result.add(tmp);

? ? ? ? }

? ? ? ? return result;

? ? }

}


//方法2:回溯法


class Solution {


? ? public List<List<Integer>> subsets(int[] nums) {

? ? ? ? List<List<Integer>> result = new ArrayList<>();

? ? ? ? List<Integer> tmp = new ArrayList<>();


? ? ? ? int step = 0;

? ? ? ? generate(step, nums, tmp, result);


? ? ? ? return result;

? ? }


? ? public void generate(int step, int[] nums, List<Integer> tmp, List<List<Integer>> result){

? ? ? ? result.add(new ArrayList<>(tmp));

? ? ? ? for(int i = step; i < nums.length; i++){

? ? ? ? ? ? tmp.add(nums[i]);

? ? ? ? ? ? generate(i+1, nums, tmp, result);

? ? ? ? ? ? tmp.remove(tmp.size()-1);

? ? ? ? }

? ? }

}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容