Given an integer array
The solution set must not contain duplicate subsets. Return the solution in any order.
nums of unique elements, return all possible subsets (the power set).The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = {1,2,3} Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Subsets {public static void main(String[] args) {int nums[] = { 1, 2, 3 };List<List<Integer>> sub = subsets(nums);System.out.println(Arrays.asList(sub));}static List<List<Integer>> subsets(int[] nums) {List<List<Integer>> res = new ArrayList<List<Integer>>();int n = nums.length;if (n == 0)return res;List<Integer> x = new ArrayList<Integer>();res.add(x);for (int i = 0; i < Math.pow(2, n); i++) {List<Integer> y = new ArrayList<Integer>();for (int j = 0; j < n; j++) {if ((i & (1 << j)) > 0)y.add(nums[j]);}if (!res.contains(y))res.add(y);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<vector<int>> subsets(vector<int>& nums){vector<vector<int>> res;int n=nums.size();if(n==0)return res;vector<int> x;res.push_back(x);for(int i=0;i<pow(2,n);i++){vector<int> y;for(int j=0;j<n;j++){if ((i & (1 << j)))y.push_back(nums[j]);}if(find(res.begin(),res.end(),y)==res.end())res.push_back(y);}return res;}int main(){vector<int> nums = {1,2,3};vector<vector<int>> sub=subsets(nums);cout<<"[";for(int i=0;i<sub.size();i++){cout<<"[";for(int j=0;j<sub[i].size();j++){cout<<sub[i][j];if(j!=sub[i].size()-1)cout<<",";}cout<<"]";if(i!=sub.size()-1)cout<<",";}cout<<"]";}
No comments:
Post a Comment