美文网首页ACM题库~
LeetCode 78. Subsets

LeetCode 78. Subsets

作者: 关玮琳linSir | 来源:发表于2017-10-26 23:06 被阅读43次

    Given a set of distinct integers, nums, return all possible subsets (the power set).

    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],
      []
    ]
    

    题意:给你一个集合,求所有的子集

    思路:深搜

    代码:

    class Solution {
        public List<List<Integer>> subsets(int[] nums) {  
            List<List<Integer>> res = new ArrayList<List<Integer>>();  
            List<Integer> temp = new ArrayList<Integer>();  
            dfs(res, temp, nums, 0);  
            return res;  
        }  
        private void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int j) {  
            res.add(new ArrayList<Integer>(temp));  
            for(int i = j; i < nums.length; i++) {  
                temp.add(nums[i]);  //① 加入 nums[i]  
                dfs(res, temp, nums, i + 1);  //② 递归  
                temp.remove(temp.size() - 1);  //③ 移除 nums[i]  
            }  
        }  
    
    }
    

    相关文章

      网友评论

        本文标题:LeetCode 78. Subsets

        本文链接:https://www.haomeiwen.com/subject/ysplpxtx.html