78. Subsets(M, dfs)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/88801884

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

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        
        for (int i = 0; i<nums.length; i++){
            dfs(ans, new ArrayList<Integer>(), nums, i);
        }
        ans.add(new ArrayList<Integer>());
        return ans;
    }
    
    public void dfs(List<List<Integer>> ans, List<Integer> temp, int[] nums, int i){
        temp.add(nums[i]);
        ans.add(temp);
        for (int j = i+1; j<nums.length; j++){
            dfs(ans, new ArrayList<Integer>(temp), nums, j);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/NCUscienceZ/article/details/88801884