Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to get the minimum path sum from top to bottom in a triangle vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm> // For std::min

int minimum_path_sum_recursion(int i, int j, int len, const std::vector<std::vector<int>>& triangle) {
    if (i == len) return 0;

    int lower_left = triangle[i][j] + minimum_path_sum_recursion(i + 1, j, len, triangle);
    int lower_right = triangle[i][j] + minimum_path_sum_recursion(i + 1, j + 1, len, triangle);
        
    return std::min(lower_left, lower_right);
}

int minimum_path_sum(const std::vector<std::vector<int>>& triangle) {
    return minimum_path_sum_recursion(0, 0, triangle.size(), triangle);
}

int main() {
    std::vector<std::vector<int>> triangle = {
         {2},
        {3, 4},
       {6, 5, 7},
     {4, 1, 8, 3}};
    
    // 2 + 3 + 5 + 1 = 11
    
    std::cout << "Minimum path sum: " << minimum_path_sum(triangle) << std::endl;
}

      
/*
run:
      
Minimum path sum: 11

*/

 



answered Aug 3, 2025 by avibootz
...