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

LeetCode 算法笔记-第 04 章 基础算法篇

1.枚举

采用枚举算法解题的一般思路如下:

  1. 确定枚举对象、枚举范围和判断条件,并判断条件设立的正确性。
  2. 一一枚举可能的情况,并验证是否是问题的解。
  3. 考虑提高枚举算法的效率。

我们可以从下面几个方面考虑提高算法的效率:

  1. 抓住问题状态的本质,尽可能缩小问题状态空间的大小。
  2. 加强约束条件,缩小枚举范围。
  3. 根据某些问题特有的性质,例如对称性等,避免对本质相同的状态重复求解。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    // Allocate memory for the result (2 integers)
    int* result = (int*)malloc(2 * sizeof(int));
    
    // Iterate through the array to find two numbers that sum to the target
    for (int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                result[0] = i; // Store the first index
                result[1] = j; // Store the second index
                *returnSize = 2; // Set the size of the result array
                return result; // Return the result array
            }
        }
    }

    *returnSize = 0; // If no solution found, set returnSize to 0
    return NULL; // Return NULL if no solution is found
}

什么是质数:大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。

int st[10000000]={0};
int pr[10000000]={0};
int cunt=0;

void pre(int n){
    cunt=0;
    for(int i=2;i<n;i++){
        if(!st[i]) pr[cunt++]=i;
        for(int j=0;pr[j]<=n/i;j++){
            st[pr[j]*i]=1;
            if(i%pr[j]==0) break;
        }
    }
}
int countPrimes(int n) {
    pre(n);
    return cunt;
}

int countTriples(int n) {
    int sun=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            for(int a=1;a<=n;a++){
                if(i*i+j*j==a*a) sun++;
            }
        }
    }
    return sun;
}

2.递归

 


http://www.kler.cn/news/310903.html

相关文章:

  • Docker vs. containerd 深度剖析容器运行时
  • 【kafka-01】kafka安装和基本核心概念
  • CSP-J算法基础 树状结构与二叉树
  • C++笔记21•C++11•
  • PyRosetta Task介绍及示例代码
  • nginx基础篇(一)
  • 算法:双指针题目练习
  • MATLAB图像处理
  • CISP备考题库(八)
  • 术语“in law”(在分布上)
  • oracle表的类型
  • 当 PC 端和移动端共用一个域名时,避免 CDN 缓存页面混乱(nginx)
  • 基于MATLAB/Simulink的模型降阶方法介绍
  • Unity射击游戏开发教程:(36)敌人关卡生成器的设计和开发
  • 【STM32系统】基于STM32设计的DAC输出电压与ADC检测电压系统(简易万用表,检测电压电流)——文末工程资料下载
  • IP协议及相关特性
  • 理解AAC和Opus的编码与解码流程
  • 企业导师面对面,产教融合实训基地搭建人才成长快车道
  • 掌握RESTful API设计:构建高效、可扩展的Web服务
  • Android Studio报错: Could not find pub.devrel:easypermissions:0.3.0, 改用linux编译
  • 在线考试|基于java的模拟考试系统小程序(源码+数据库+文档)
  • Modbus_RTU和Modbus库
  • 1.Seata 1.5.2 seata-server搭建
  • 线程池的类型和状态
  • sqli-labs靶场自动化利用工具——第11关
  • 【深度学习】(2)--PyTorch框架认识
  • 设计模式(Design Patterns)
  • springBoot整合mybatisplus
  • 学习风格的类型
  • 内核是如何接收网络包的