LeetCode--78--子集

題目描述:
給定一組不含重複元素的整數數組 nums,返回該數組所有可能的子集(冪集)。
輸入:
nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
題意:
題目描述
題解
簡單dfs
直接爆搜即可
代碼:

class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        int len = nums.length;
        for(int i = 0; i <= len; i ++){
            List<Integer> list = new ArrayList<>();
            subsets_dfs(-1,i,nums,list);
        }
        return ans;
    }

    public void subsets_dfs(int st,int num,int [] nums,List<Integer> list){
        if(num == 0){
            ans.add(new ArrayList<>(list));
            return ;
        }
        for(int i = st + 1; i < nums.length; i ++){
            list.add(nums[i]);
            subsets_dfs(i,num -1 ,nums,list);
            list.remove(list.size() - 1);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章