惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
A
About on SuperTechFans
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 叶小钗
博客园 - 聂微东
博客园 - Franky
Apple Machine Learning Research
Apple Machine Learning Research
罗磊的独立博客
量子位
博客园 - 三生石上(FineUI控件)
Recent Announcements
Recent Announcements
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
T
The Blog of Author Tim Ferriss
GbyAI
GbyAI
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Word Break II | Backtracking
Jaspreet singh · 2026-06-19 · via DEV Community

Jaspreet singh

Problem Statement

Given a string s and a dictionary wordDict, return all possible sentences where:

  • Every word exists in the dictionary.
  • Spaces can be inserted anywhere valid.

Return all valid sentences.


Brute Force Intuition

Try every possible cut in the string.

For every substring:

Check if it exists in dictionary

If yes:

Take it
Recursively solve remaining string

If no:

Skip it

This naturally forms a recursion tree.

Complexity

  • Time Complexity: Exponential
  • Space Complexity: O(N)

Moving Towards the Optimal Approach

Instead of generating every partition first:

At every index:

Try all possible substrings

Only continue if:

substring ∈ dictionary

This prunes many invalid paths.

Using a HashSet makes word lookup O(1).


Pattern Recognition

Whenever you see:

  • String partitioning
  • Dictionary lookup
  • Return all valid ways

Think:

Backtracking + HashSet


Key Observation

Example:

s = "catsanddog"

dict = ["cat","cats","and","sand","dog"]

At index 0:

"c"      ❌
"ca"     ❌
"cat"    ✅
"cats"   ✅

Only valid words create recursive branches.


Recursive Tree

catsanddog

          ""
        /    \
     cat     cats
      |        |
    sand      and
      |        |
     dog      dog
      |        |
 cat sand dog
 cats and dog


Optimal Java Solution

import java.util.*;

class Solution {

    public List<String> wordBreak(String s,
                                  List<String> wordDict) {

        List<String> ans = new ArrayList<>();

        Set<String> dict = new HashSet<>(wordDict);

        solve(0, s, dict, "", ans);

        return ans;
    }

    private void solve(int index,
                       String s,
                       Set<String> dict,
                       String sentence,
                       List<String> ans) {

        if (index == s.length()) {

            ans.add(sentence.trim());

            return;
        }

        for (int end = index; end < s.length(); end++) {

            String word =
                s.substring(index, end + 1);

            if (dict.contains(word)) {

                solve(end + 1,
                      s,
                      dict,
                      sentence + word + " ",
                      ans);
            }
        }
    }
}


Dry Run

Input

s = "catsanddog"

dict =
["cat","cats","and","sand","dog"]


Path 1

cat
 ↓
sand
 ↓
dog

Sentence:

"cat sand dog"


Path 2

cats
 ↓
and
 ↓
dog

Sentence:

"cats and dog"


Output

[
 "cat sand dog",
 "cats and dog"
]


Why Backtracking Works?

At every index:

Try every possible word

If the word exists in dictionary:

Choose
Explore
Backtrack

Eventually all valid sentence combinations are generated.


Optimization (Interview Follow-up)

The same suffix may be solved repeatedly.

Example:

dog

can be reached through multiple paths.

Use:

HashMap<String, List<String>>

for memoization.

This converts the solution into:

Backtracking + DP

and significantly improves performance.


Complexity Analysis

Metric Complexity
Time Complexity Exponential
Space Complexity O(N)

Without memoization, many suffixes are recomputed.


Interview One-Liner

At every index, try all possible substrings. If the substring exists in the dictionary, recursively generate sentences from the remaining string and append the current word.


Pattern Learned

String
+
Dictionary
+
All Valid Partitions

=> Backtracking

Similar Problems

  • Word Break II
  • Palindrome Partitioning
  • Restore IP Addresses
  • Expression Add Operators
  • Letter Case Permutation

Memory Trick

Subsets
→ Pick / Not Pick

Palindrome Partitioning
→ Try Every Cut

Word Break II
→ Try Every Word

Mental Model

Current Index
      ↓
Try Every Substring
      ↓
Word Exists ?
      ↓
Take It
      ↓
Recurse

Whenever you hear:

"Return all possible sentences"

your brain should immediately think:

Backtracking + Dictionary Lookup + Try Every Cut 🚀