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

推荐订阅源

罗磊的独立博客
I
InfoQ
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
云风的 BLOG
云风的 BLOG
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
The GitHub Blog
The GitHub Blog
博客园_首页
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
G
Google Developers Blog
WordPress大学
WordPress大学
B
Blog
人人都是产品经理
人人都是产品经理
小众软件
小众软件
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
量子位
Apple Machine Learning Research
Apple Machine Learning Research
N
Netflix TechBlog - Medium
Last Week in AI
Last Week in AI
博客园 - 聂微东
Jina AI
Jina AI

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
Combination Sum | Backtracking
Jaspreet singh · 2026-06-17 · via DEV Community

Jaspreet singh

Problem Statement

Given an array of distinct integers candidates and a target value target, return all unique combinations where the chosen numbers sum to the target.

A number may be chosen unlimited times.


Brute Force Intuition

For every element, we have two choices:

Pick it
Skip it

If we pick an element, we can pick it again because repetitions are allowed.

We keep exploring all possible combinations until:

  • Target becomes 0 → Valid combination
  • Target becomes negative → Invalid path

Pattern Recognition

Whenever you see:

  • Generate all possible combinations
  • Target Sum
  • Unlimited usage of elements

Think:

Backtracking + Pick / Not Pick


Key Observation

Unlike Subsets:

After picking an element,
we stay at the same index.

Why?

Because the same element can be used multiple times.

Example:

candidates = [2,3,6,7]
target = 7

To form:

[2,2,3]

we must be able to pick 2 repeatedly.


Optimal Java Solution

import java.util.*;

class Solution {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

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

        helper(0, candidates, target, ans, new ArrayList<>());

        return ans;
    }

    private void helper(int index,
                        int[] candidates,
                        int target,
                        List<List<Integer>> ans,
                        List<Integer> ds) {

        if (target == 0) {
            ans.add(new ArrayList<>(ds));
            return;
        }

        if (index == candidates.length) {
            return;
        }

        // Pick
        if (candidates[index] <= target) {

            ds.add(candidates[index]);

            helper(index,
                   candidates,
                   target - candidates[index],
                   ans,
                   ds);

            ds.remove(ds.size() - 1);
        }

        // Not Pick
        helper(index + 1,
               candidates,
               target,
               ans,
               ds);
    }
}


Dry Run

Input

candidates = [2,3,6,7]
target = 7

Recursion Tree

7

Pick 2
|
5

Pick 2
|
3

Pick 2
|
1 (Invalid)

Backtrack

Pick 3
|
0 ✅

Combination:

[2,2,3]

Another path:

Pick 7
|
0 ✅

Combination:

[7]

Output

[
 [2,2,3],
 [7]
]


Why Staying on Same Index Works?

When we pick:

candidates[index]

we call:

helper(index, ...)

instead of:

helper(index + 1, ...)

This allows:

2 → 2 → 2

or any number of repeated selections.

Without this, each number could be used only once.


Complexity Analysis

Metric Complexity
Time Complexity O(2^T) (Exponential)
Space Complexity O(T)

Where:

T = Target

Recursion depth can grow up to target in worst case.


Interview One-Liner

Use backtracking with Pick / Not Pick. When picking an element, stay at the same index because elements can be reused multiple times.


Pattern Learned

Target Sum
+
Generate All Combinations
+
Unlimited Usage Allowed

=> Backtracking
=> Pick / Not Pick
=> Stay on Same Index After Pick

Similar Problems

  • Combination Sum
  • Coin Change (Generate Ways)
  • Unbounded Knapsack
  • Rod Cutting
  • Integer Break