Pascal's Triangle Java Solution LeetCode

🚀 LeetCode #118 – Pascal’s Triangle | Java Solution Today I solved the classic Pascal’s Triangle problem — a great exercise to strengthen understanding of lists, iteration, and dynamic building of data structures. 📌 Problem Summary Given an integer numRows, generate the first numRows of Pascal’s Triangle. Each element is the sum of the two elements directly above it. 💡 Approach I Used Start with the first row [1] For each new row: First and last elements are always 1 Middle elements = sum of previous row elements Build row by row using a loop 🧠 Key Learning Handling nested lists (List<List<Integer>>) Using previous computation to build the next (Dynamic Thinking) Clean iteration logic 💻 Java Code Snippet for(int i = 1; i < numRows; i++){ List<Integer> prev = resultList.get(i - 1); List<Integer> curr = new ArrayList<>(); curr.add(1); for(int j = 1; j < i; j++){ curr.add(prev.get(j - 1) + prev.get(j)); } curr.add(1); resultList.add(curr); } 📊 Output Example (numRows = 5): [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] Happy Coding 😊; #LeetCode #Java #DSA #CodingJourney #ProblemSolving #SoftwareDevelopment #100DaysOfCode

  • text

To view or add a comment, sign in

Explore content categories