leetcode 78. Subsets DFS深度优先搜索

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

这道题和上一道题的做法很类似, leetcode 77. Combinations 按照index递归搜索+全排列做法leetcode 90. Subsets II DFS深度优先搜索 + 全排列 一起学习

这两道题应该放到一起学习。

代码如下:

import java.util.ArrayList;
import java.util.List;

public class Solution 
{
    List<List<Integer>> res=new ArrayList<List<Integer>>();
    public List<List<Integer>> subsets(int[] nums)
    {
        if(nums==null || nums.length<=0)
        {
            res.add(new ArrayList<Integer>());
            return res;
        }

        List<Integer> one=new ArrayList<>();
        getFullPute(nums,one,0);
        return res;
    }

    private void getFullPute(int[] nums,List<Integer> one, int i)
    {
        if(i==nums.length)
        {
            res.add(new ArrayList<Integer>(one));
        }else
        {
            //第一次递归调用是不选择当前元素的递归
            getFullPute(nums, one, i+1);

            //第二次递归调用是选择当前元素的调用
            one.add(nums[i]);
            getFullPute(nums, one, i+1);
            one.remove(one.size()-1);
        }

    }

    //其实还有另一种思想,使用一个flag数组,长度为nums的length,其中flag[i]为0表示添加该元素,为
    //0表示不添加,这个也可以使用递归实现,和上面的方法类似
}

下面是C++的做法,和上一道题一模一样,就是一个DFS深度优先遍历搜索的做法

代码如下:

#include <iostream>
#include <vector>

using namespace std;

class Solution
{
public:
    vector<vector<int>> res;
    vector<vector<int>> subsets(vector<int>& nums) 
    {
        if (nums.size() <= 0)
            return res;

        vector<int> one;
        getAllByDFS(nums, 0, one);
        return res;
    }

    void getAllByDFS(vector<int>& nums, int index, vector<int>& one)
    {
        if (index == nums.size())
        {
            res.push_back(one);
            return;
        }
        else
        {
            getAllByDFS(nums, index + 1, one);

            one.push_back(nums[index]);
            getAllByDFS(nums, index + 1, one);
            one.erase(one.end() - 1);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值