动态规划 Leetcode 139 单词拆分

单词拆分

Leetcode 139

学习记录自代码随想录

要点在注释中详细说明,注意迭代公式中是dp[i]不是dp[j-i]

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>


bool wordBreak(char* s, char** wordDict, int wordDictSize) {

    // 1.dp[j]代表背包容量为字符串s的长度j时是否可以利用字典中单词拼接为字符串s,dp[j]为true和false,
    bool dp[strlen(s)+1];
    memset(dp, false, sizeof(dp));
    // 2.递推公式,if(j到i之间的字符串在wordDict中 && dp[j-i]为true) 则dp[j]为true
    // 3.dp数组初始化,dp[0] = true;
    dp[0] = true;
    // 4.遍历顺序,本题中字符串组合顺序不能改变所以实际上是排列问题,所以先遍历背包,再遍历物品
    for(int j = 0; j < strlen(s)+1; j++){
        for(int i = 0; i < j; i++){
            int length = j - i;
            char sub_str[length+1];
            strncpy(sub_str, s+i, length);
            sub_str[length] = '\0';
            for(int k = 0; k < wordDictSize; k++){
                if((strcmp(wordDict[k], sub_str) == 0) && dp[i]){
                    dp[j] = true;
                }
            }
            
        }
    }
    // 5.举例推导dp数组
    return dp[strlen(s)];
}

int main(){
    int n;
    scanf("%d", &n);
    while(n){
        char s[301];
        scanf("%s", &s);
        int wordDictSize;
        scanf("%d", &wordDictSize);
        char** wordDict = (char**)malloc((wordDictSize) * sizeof(char*));
        for(int i = 0; i < wordDictSize; i++){
            wordDict[i] = (char*)malloc(21 * sizeof(char));
            scanf("%s", wordDict[i]);
        }
        bool result = wordBreak(s, wordDict, wordDictSize);
        printf("%d", result);
        for(int i = 0; i < wordDictSize; i++){
            free(wordDict[i]);
        }
        free(wordDict);
    }
    return 0;
}

相关推荐

  1. 动态规划 Leetcode 139 单词

    2024-03-21 20:48:04       38 阅读
  2. 动态规划Leetcode 139. 单词【中等】

    2024-03-21 20:48:04       35 阅读
  3. Leetcode 139 单词

    2024-03-21 20:48:04       54 阅读
  4. leetcode 139. 单词

    2024-03-21 20:48:04       38 阅读
  5. LeetCode 139. 单词

    2024-03-21 20:48:04       37 阅读
  6. LeetCode热题100】【动态规划单词

    2024-03-21 20:48:04       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-21 20:48:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-21 20:48:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-21 20:48:04       82 阅读
  4. Python语言-面向对象

    2024-03-21 20:48:04       91 阅读

热门阅读

  1. pycharm专业版破解亲测可用记录一下

    2024-03-21 20:48:04       39 阅读
  2. 安卓面试题多线程 121-125

    2024-03-21 20:48:04       41 阅读
  3. C 练习实例83-求0—7所能组成的奇数个数

    2024-03-21 20:48:04       42 阅读
  4. 【vue自定义指令touch-move】

    2024-03-21 20:48:04       37 阅读
  5. 收集一些PostgreSQL的题目

    2024-03-21 20:48:04       46 阅读
  6. VHDL设计实现数字扫雷游戏及仿真

    2024-03-21 20:48:04       33 阅读
  7. 【ceph】配置 ceph dashboard 详细配置过程

    2024-03-21 20:48:04       34 阅读
  8. Apache Spark 的基本概念和在大数据分析中的应用

    2024-03-21 20:48:04       38 阅读
  9. Docker

    2024-03-21 20:48:04       37 阅读