动态规划 Leetcode 139 单词拆分

单词拆分

Leetcode 139

学习记录自代码随想录

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

c 复制代码
#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;
}
相关推荐
灰灰勇闯IT9 分钟前
【探索实战】Kurator多集群统一应用分发实战:从环境搭建到业务落地全流程
算法
鱼在树上飞17 分钟前
乘积最大子数组
算法
H_z___32 分钟前
Codeforces Round 1070 (Div. 2) A~D F
数据结构·算法
自学小白菜1 小时前
每周刷题 - 第三周 - 双指针专题 - 02
python·算法·leetcode
杜子不疼.1 小时前
【LeetCode76_滑动窗口】最小覆盖子串问题
算法·哈希算法
ComputerInBook1 小时前
代数基本概念理解——特征向量和特征值
人工智能·算法·机器学习·线性变换·特征值·特征向量
不能只会打代码1 小时前
力扣--3433. 统计用户被提及情况
java·算法·leetcode·力扣
biter down2 小时前
C++ 解决海量数据 TopK 问题:小根堆高效解法
c++·算法
用户6600676685392 小时前
斐波那契数列:从递归到缓存优化的极致拆解
前端·javascript·算法
初夏睡觉2 小时前
P1055 [NOIP 2008 普及组] ISBN 号码
算法·p1055