Permutations Backtracking Java Solution

🚀 LeetCode #46 — Permutations (Backtracking in Java) Today I solved the Permutations problem using a clean swap-based backtracking approach. This problem is a great way to strengthen recursion and understand how backtracking explores all possible configurations systematically. 🧠 Problem Summary Given an array of distinct integers, generate all possible permutations. 💡 Approach Instead of using extra space to track used elements, I applied in-place swapping: Fix one index at a time Swap it with every possible candidate Recurse for the next index Backtrack (swap back) to restore the original order This ensures: ✔ All permutations are explored ✔ No duplicates ✔ Efficient space usage ✅ Java Solution class Solution { List<List<Integer>> sol = new ArrayList<>(); public List<List<Integer>> permute(int[] nums) { generate(0, nums); return sol; } public void generate(int i, int[] nums) { if (i == nums.length) { sol.add(Arrays.stream(nums).boxed().toList()); return; } for (int j = i; j < nums.length; j++) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; generate(i + 1, nums); temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } 📈 Complexity Time: O(n × n!) Space: O(n) recursion depth 🔍 Key Learnings ✨ Backtracking = Choose → Explore → Unchoose ✨ Swapping helps avoid extra memory usage ✨ Restoring state is critical for correct recursion Problems like this really improve intuition for recursion trees and algorithmic thinking. #LeetCode #Java #Backtracking #Recursion #DataStructures #Algorithms #CodingPractice #ProblemSolving #LearningJourney

To view or add a comment, sign in

Explore content categories