当前位置: 首页 > news >正文

子集

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

回溯算法,递归的时候只能将后面的元素进栈。

/**
 * 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 sub(int** a,int* s,int* nums,int* top,int *rear,int n,int index,int* col)
{
    int i,j;
    for(i=index;i<n;i++)
    {
        s[*top]=nums[i];
        (*top)++;
        col[*rear]=*top;
        a[*rear]=(int *)malloc(sizeof(int)*(*top));
        for(j=0;j<*top;j++)
            a[*rear][j]=s[j];
        (*rear)++;
        sub(a,s,nums,top,rear,n,i+1,col);
        (*top)--;
    }
}
int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {
    int size=pow(2,numsSize);
    *returnSize=size;
    int **a=(int **)malloc(sizeof(int *)*size);
    a[0]=(int *)malloc(sizeof(int)); // if dont do this,wont be able to alloc next array
    *columnSizes=(int *)malloc(sizeof(int)*size);
    (*columnSizes)[0]=0;
    int *s=(int *)malloc(sizeof(int)*numsSize);
    int top=0,rear=1;
    sub(a,s,nums,&top,&rear,numsSize,0,*columnSizes);
    return a;
}

转载于:https://www.cnblogs.com/onlyandonly/p/9332505.html

相关文章:

  • 源码编译安装LNMP环境及配置基于域名访问的多虚拟主机
  • Linux各目录及每个目录的详细介绍
  • 90分 蓝桥杯 算法提高 道路和航路 [ 最短路 ]
  • linux一次卸载多个软件
  • 《大话数据结构》读书笔记(一)
  • Tyvj3632|超级英雄Hero
  • 如何从mysql数据库中取到随机的记录
  • soapUI使用-DataSource获取oracle库中的参数
  • POJ - 1584 A Round Peg in a Ground Hole(判断凸多边形,点到线段距离,点在多边形内)...
  • 生产服务器环境最小化安装后 Centos 6.5优化配置备忘
  • 基于阿里云数加构建企业级数据分析平台
  • 关于 来源: volmgr Event ID: 46 故障转储初始化未成功 的问题
  • 深入理解计算机操作系统(十)
  • 机器学习数据挖掘笔记_16(常见面试之机器学习算法思想简单梳理)
  • tornado
  • 9月CHINA-PUB-OPENDAY技术沙龙——IPHONE
  • 收藏网友的 源程序下载网
  • 【编码】-360实习笔试编程题(二)-2016.03.29
  • 30天自制操作系统-2
  • Android 控件背景颜色处理
  • Apache的基本使用
  • codis proxy处理流程
  • Git同步原始仓库到Fork仓库中
  • Intervention/image 图片处理扩展包的安装和使用
  • jQuery(一)
  • leetcode-27. Remove Element
  • MySQL常见的两种存储引擎:MyISAM与InnoDB的爱恨情仇
  • MySQL数据库运维之数据恢复
  • tweak 支持第三方库
  • 分享自己折腾多时的一套 vue 组件 --we-vue
  • 基于Volley网络库实现加载多种网络图片(包括GIF动态图片、圆形图片、普通图片)...
  • 极限编程 (Extreme Programming) - 发布计划 (Release Planning)
  • 聊聊flink的TableFactory
  • 七牛云假注销小指南
  • 嵌入式文件系统
  • 人脸识别最新开发经验demo
  • 我建了一个叫Hello World的项目
  • 小程序滚动组件,左边导航栏与右边内容联动效果实现
  • 怎样选择前端框架
  • 正则表达式
  • 【运维趟坑回忆录 开篇】初入初创, 一脸懵
  • #HarmonyOS:基础语法
  • #Lua:Lua调用C++生成的DLL库
  • (14)Hive调优——合并小文件
  • (C++17) std算法之执行策略 execution
  • (二)springcloud实战之config配置中心
  • (二)正点原子I.MX6ULL u-boot移植
  • (附源码)ssm基于微信小程序的疫苗管理系统 毕业设计 092354
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (十八)SpringBoot之发送QQ邮件
  • (转)程序员技术练级攻略
  • ***详解账号泄露:全球约1亿用户已泄露
  • .L0CK3D来袭:如何保护您的数据免受致命攻击
  • .NET Core、DNX、DNU、DNVM、MVC6学习资料
  • @EnableAsync和@Async开始异步任务支持