How to Generate Permutations of an Array with Repetition in Java

Question

How can I generate permutations of an array, allowing for repetition, using Java?

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

public class Permutations {
    public static List<List<Integer>> permute(int[] nums, int repeatTime) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<Integer>(), nums, repeatTime);
        return result;
    }

    private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int repeatTime) {
        if (tempList.size() == repeatTime) {
            result.add(new ArrayList<>(tempList));
        } else {
            for (int num : nums) {
                tempList.add(num);
                backtrack(result, tempList, nums, repeatTime);
                tempList.remove(tempList.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> permutations = permute(nums, 2);
        System.out.println(permutations);
    }
}

Answer

Generating permutations of an array with repetition in Java can be achieved through a recursive approach using backtracking. This allows us to explore all possible combinations of the elements of the array, given a specified length for the permutations.

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

public class Permutations {
    public static List<List<Integer>> permute(int[] nums, int repeatTime) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<Integer>(), nums, repeatTime);
        return result;
    }

    private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int repeatTime) {
        if (tempList.size() == repeatTime) {
            result.add(new ArrayList<>(tempList));
        } else {
            for (int num : nums) {
                tempList.add(num);
                backtrack(result, tempList, nums, repeatTime);
                tempList.remove(tempList.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> permutations = permute(nums, 2);
        System.out.println(permutations);
    }
}

Causes

  • Understanding that repetition allows the same element to appear multiple times in combinations.
  • Familiarity with recursive algorithms and backtracking techniques.

Solutions

  • Implement a recursive function to generate permutations.
  • At each recursive call, add elements to the current permutation and track the size until it reaches the desired length.
  • Remove the last added element after exploring one level of recursion to backtrack.

Common Mistakes

Mistake: Not considering the base case properly in recursion.

Solution: Ensure the recursion stops when the length of the current permutation matches the desired length.

Mistake: Failing to reset the state after each recursion step.

Solution: Always remove the last added element after exploring one possibility to avoid incorrect states.

Helpers

  • Java permutations with repetition
  • generate permutations Java
  • Java backtracking
  • recursive permutations
  • integer array permutations Java

Related Questions

⦿What Happens When the Size of the String Pool Exceeds in Java?

Explore the implications of exceeding the Java String Pool size including causes solutions and coding best practices.

⦿How to Find the Path of a Text File in a NetBeans Java Project?

Learn how to locate the path of a text file in a NetBeans Java project with expert tips and sample code. Enhance your Java programming skills today

⦿Does Closing a DataInputStream Also Close Its Underlying FileInputStream?

Learn whether closing a DataInputStream automatically closes the associated FileInputStream and best practices for resource management.

⦿How to Handle Special Characters like \0 (NUL) in Java?

Learn how to manage special characters such as 0 NUL in Java. Explore common issues solutions and best practices for handling these characters effectively.

⦿How to Mock an Interface with Mockito and Handle NullPointerExceptions

Learn how to effectively mock interfaces in Mockito and prevent NullPointerExceptions with our expert guide.

⦿Do I Need to Annotate Every Class in an Object Graph with @Inject in Guice?

Explore if its necessary to annotate every class in a Guice object graph with Inject and learn how dependency injection works effectively.

⦿How to Properly Install JAR Files on macOS for Java Applications?

Learn where and how to install JAR files on macOS so they can be recognized by other Java applications. Follow our guide for best practices.

⦿How to Override Spring `message` Tag with Database Values?

Learn how to dynamically override Springs message tag using values from a database for improved localization in your application.

⦿How to Return an ArrayList from a WebService in Java

Learn how to effectively return an ArrayList from a Java WebService including code examples common mistakes and debugging tips.

⦿How to Detect Changes in JScrollPane Scroll Bar Visibility in Java?

Learn how to detect the visibility changes of scroll bars in JScrollPane using Java. Explore detailed solutions and code examples.

© Copyright 2025 - CodingTechRoom.com