How to Implement a Non-Recursive Permutation Algorithm in Java?

Question

What is a non-recursive way to generate permutations in Java?

public static List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> result = new ArrayList<>();
    Stack<List<Integer>> stack = new Stack<>();
    stack.push(new ArrayList<>());
    boolean[] used = new boolean[nums.length];

    while (!stack.isEmpty()) {
        List<Integer> current = stack.pop();

        if (current.size() == nums.length) {
            result.add(new ArrayList<>(current));
            continue;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue;
            used[i] = true;
            current.add(nums[i]);
            stack.push(new ArrayList<>(current));
            current.remove(current.size() - 1);
            used[i] = false;
        }
    }
    return result;
}

Answer

Generating permutations without recursion can be achieved using an iterative approach. This method leverages a stack data structure to maintain the current state of permutations as we explore possible combinations in a controlled manner.

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Permutations {
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Stack<List<Integer>> stack = new Stack<>();
        stack.push(new ArrayList<>());
        boolean[] used = new boolean[nums.length];

        while (!stack.isEmpty()) {
            List<Integer> current = stack.pop();

            if (current.size() == nums.length) {
                result.add(new ArrayList<>(current));
                continue;
            }

            for (int i = 0; i < nums.length; i++) {
                if (used[i]) continue;
                used[i] = true;
                current.add(nums[i]);
                stack.push(new ArrayList<>(current));
                current.remove(current.size() - 1);
                used[i] = false;
            }
        }
        return result;
    }
}

Causes

  • Need for efficient memory management without the overhead of recursion.
  • Preference for iterative methods in certain programming scenarios.

Solutions

  • Utilize a stack to emulate the call stack used in recursive methods.
  • Maintain a boolean array to track which elements are currently used in the permutation.

Common Mistakes

Mistake: Not properly managing the 'used' state, causing duplicates in results.

Solution: Ensure to reset used[i] to false after backtracking.

Mistake: Attempting to use stack.push(current) without creating a new list causes reference issues.

Solution: Always instantiate a new ArrayList for stack entries.

Helpers

  • Java non-recursive permutation
  • iterative permutation algorithm Java
  • Java permutations without recursion
  • generate permutations Java

Related Questions

⦿How to Resolve the `java.lang.UnsatisfiedLinkError: Could not find DSO to load: libreactnativejni.so` in React Native on Android

Learn how to troubleshoot and fix java.lang.UnsatisfiedLinkError for libreactnativejni.so in React Native Android apps. Expert solutions and tips included.

⦿Why Is It Not Possible to Reduce Method Visibility in a Java Subclass?

Explore the reasons why method visibility cannot be reduced in Java subclasses along with explanations and best practices for Java inheritance.

⦿How to Use TrueType Fonts in libGDX?

Learn how to effectively use TrueType fonts in libGDX including setup code snippets and common issues.

⦿What is the .NET Equivalent of Java's StringBuffer?

Discover the .NET equivalent of StringBuffer in Java including its usage performance comparison and best practices.

⦿How to Select an Item from a Dropdown List Using Selenium WebDriver in Java?

Learn how to select dropdown items using Selenium WebDriver with Java. Stepbystep guide and code snippets included for better understanding.

⦿How to Implement Multipart File Upload in Spring Boot

Learn how to effectively implement multipart file upload in Spring Boot with detailed steps and code examples.

⦿How to Handle DropDown Boxes Using Selenium WebDriver?

Learn how to effectively interact with dropdown boxes in Selenium WebDriver with stepbystep guidance and examples.

⦿Can Java Call Parent Overridden Methods from Other Objects but Not from Subtypes?

Explore if Java allows calling parent overridden methods from different object instances excluding subtypes with detailed explanations and examples.

⦿How to Simultaneously Write Data to Multiple java.io.OutputStream Instances?

Learn how to write data to multiple OutputStream objects simultaneously in Java with expert techniques and code examples.

⦿What is a Java Interpreter and How Does It Work?

Explore the concept of a Java interpreter its functionality and its role in Java application execution. Learn about differences with compilers.

© Copyright 2025 - CodingTechRoom.com