leetcode----78. Subsets

链接:

https://leetcode.com/problems/subsets/

大意:

给定一个由整数数组表示而成的集合nums,nums中没有重复的数字。要求求出集合nums的所有子集。注:空集是任何集合的子集。例子:

思路:

回溯法。

代码:

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        res.add(new LinkedList<>());
        if(nums.length == 0)
            return res;
        dfs(nums, res, new LinkedList<>(), 0);
        return res;
    }
    public void dfs(int[] nums, List<List<Integer>> res, LinkedList<Integer> list, int index) {
        for (int i = index; i < nums.length; i++) {
            list.addLast(nums[i]);
            res.add(new ArrayList<>(list));
            dfs(nums, res, list, i + 1);
            list.removeLast();
        }
    }
}

结果:

结论:

基本回溯题。 

 

猜你喜欢

转载自blog.csdn.net/smart_ferry/article/details/88965107