LeetCode 78. 子集【c++/java详细题解】
目录
- 1、题目
- 2、思路1
- 3、c++代码1
- 4、java代码1
- 5、思路2
- 6、c++代码2
- 7、java代码2
1、题目
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10-10 <= nums[i] <= 10nums中的所有元素 互不相同
2、思路1
(二进制) O ( 2 n n ) O(2^nn) O(2nn)
对于一个大小为n的数组nums来说,由于每个数有选和不选两种情况,因此总共有 2 n 2^n 2n 种情况。我们用n位二进制数 0 0 0 到 2 n − 1 2^n-1 2n−1 表示每个数的选择状态情况,在某种情况i中,若该二进制数i的第j位是1,则表示nums数组第j位这个数选,我们将nums[j]加入到path中,枚举完i这种情况,将path加入到res中 。
例如对于集合[1, 2, 3]
| 0/1序列 | 表示集合 | 对应的二进制数 |
|---|---|---|
| 000 | [] | 0 |
| 001 | [3] | 1 |
| 010 | [2] | 2 |
| 011 | [2, 3] | 3 |
| 100 | [1] | 4 |
| 101 | [1, 3] | 5 |
| 110 | [1, 2] | 6 |
| 111 | [1, 2, 3] | 7 |
3、c++代码1
class Solution {
public:vector<vector<int>> subsets(vector<int>& nums) {vector<vector<int>>res;int n = nums.size();for(int i = 0; i < 1<<n; i++){vector<int>path;for(int j = 0; j < n; j++){if(i>>j&1)path.push_back(nums[j]);}res.push_back(path);}return res;}
};
4、java代码1
class Solution {static List<List<Integer>> res = new ArrayList<List<Integer>>();static List<Integer> path = new ArrayList<Integer>();public List<List<Integer>> subsets(int[] nums) {int n = nums.length;for(int i = 0;i < 1 << n;i ++){path.clear();for(int j = 0;j < n;j ++){if((i >> j & 1) == 1)path.add(nums[j]);}res.add(new ArrayList<Integer>(path));}return res;}
}
时间复杂度分析: 一共枚举 2 n 2^n 2n 个数,每个数枚举 n n n 位,所以总时间复杂度是 O ( 2 n n ) O(2^nn) O(2nn)。
5、思路2
(递归) O ( 2 n n ) O(2^nn) O(2nn)
一共n个位置,递归枚举每个位置的数 选 还是 不选,然后递归到下一层。
递归函数设计
- 递归参数:
void dfs(vector,第一个参数是& nums, int u) nums数组,第二个参数是u,表示当前枚举到nums数组中的第u位。 - 递归边界:
u == nums.size(),当枚举到第nums.size()位时,递归结束,我们将结果放到答案数组res中。
时间复杂度分析: 一共 2 n 2^n 2n 个状态,每种状态需要 O ( n ) O(n) O(n) 的时间来构造子集。
6、c++代码2
class Solution {
public:vector<vector<int>>res;vector<int>path;vector<vector<int>> subsets(vector<int>& nums) {dfs(nums,0);return res;}void dfs(vector<int>&nums,int u){if( u == nums.size()) //递归边界{res.push_back(path);return;}dfs(nums,u+1); //不选第u位,递归下一层path.push_back(nums[u]);dfs(nums,u+1); //选第u位,递归下一层path.pop_back(); //回溯}
};
7、java代码2
class Solution {List<List<Integer>> res= new ArrayList<List<Integer>>();List<Integer> path = new ArrayList<Integer>();public List<List<Integer>> subsets(int[] nums) {dfs(nums,0);return res;}public void dfs(int[] nums,int u) {if (u == nums.length) {res.add(new ArrayList<Integer>(path));return;}dfs(nums,u + 1);path.add(nums[u]);dfs(nums,u + 1);path.remove(path.size() - 1);}
}
原题链接: 78. 子集

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
