题目描述:
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
题目解答:
方法1:回溯算法
循环加递归。临时数字每更新一次数字就存储一次。
运行时间ms,代码如下。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
void dfs(int*** result, int* size, int** column, int* nums, int n, int* use, int used, int start) {
int i = 0;
for(i = start; i < n; i++) {
use[used] = nums[i];
(*size)++;
column[0] = (int*)realloc(column[0], *size * sizeof(int));
column[0][*size - 1] = used + 1;
result[0] = (int**)realloc(result[0], *size * sizeof(int*));
result[0][*size - 1] = (int*)malloc((used + 1) * sizeof(int));
memcpy(result

这篇博客讨论了LeetCode的78题,即如何找出整数数组的所有子集(幂集)。博主提供了三种解法:回溯算法、迭代和位运算。每种方法都详细解释了思路,并附有运行时间。对于回溯算法,通过递归和临时存储来找到所有子集;迭代方法通过增加前n个子集的元素数量达到目的;位运算是将问题转换为遍历,根据数字的位来决定是否选中数组元素。
&spm=1001.2101.3001.5002&articleId=85649569&d=1&t=3&u=a64147a79bb748fda1d09acfe0b7a6ab)
640

被折叠的 条评论
为什么被折叠?



