Skip to main content

Command Palette

Search for a command to run...

permuation

Published
1 min readView as Markdown
import java.util.*;

public class PermutationsExample {

    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        backtrack(nums, new ArrayList<>(), used, result);
        return result;
    }

    private static void backtrack(int[] nums, 
    List<Integer> path, boolean[] used,
     List<List<Integer>> result) {
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path)); // ✅ add copy
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!used[i])
            {
            // choose
            used[i] = true;
            path.add(nums[i]);
            // explore
            backtrack(nums, path, used, result);
            // unchoose (backtrack)
            path.remove(path.size() - 1);
            used[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};  // ✅ You can change this

        List<List<Integer>> permutations = permute(nums);

        System.out.println("All permutations:");
        for (List<Integer> perm : permutations) {
            System.out.println(perm);
        }
    }
}

More from this blog

Amit singh's blog

235 posts