← Accenture bank

Accenture · Question 59 · Backtracking

Combination Sum

BacktrackingC++code⏱ O(N^(T/M+1))💾 O(T/M)
Service-based

Problem

Find all unique combinations of candidates where the chosen nu mbers sum to target.

Approach

Use backtracking, allowing repeated candidates.

Time O(N^(T/M+1))Space O(T/M)

How it works

  1. 1Sort to prune overshooting branches.
  2. 2Reuse allowed: recurse from the same index.

Sample input / output

Input:
candidates = [2, 3, 6, 7], target = 7
Output:
[[2, 2, 3], [7]]

Constraints

Distinct candidates; 1 <= target <= 500.

Solution — read it, then walk it

Time O(N^(T/M+1))Space O(T/M)Loops 3Branches 4Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <algorithm>using namespace stdDEFINEbacktrack(std::vector<int>&candidates, int target, in…std::vector<int>& current,std::vector<std::vector<int>>&res)if (target == 0)res.push_back(current)RETURNfor (size_t i = start;i < candidates.size();++i)if (candidates[i] >target) breakcurrent.push_back(candidates[i])backtrack(candidates,target - candidates[i], i,current, res)current.pop_back()std::vector<std::vector<int>>combinationSum(std::vector<int>&candidates, int target)DEFINE main()std::vector<int> c = {2, 3,6, 7}auto r = combinationSum(c,7)cout << "["for (size_t i = 0; i <r.size(); ++i)if (i) cout << ", "cout << "["for (size_t j = 0; j <r[i].size(); ++j)if (j) cout << ", "cout << r[i][j]cout << "]"cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/29

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits