public class Permutations {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};

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

        System.out.println(ans.toString());
    }

    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return ans;
        }

        recurse(nums, ans, 0);

        return ans;
    }

    private static void recurse(int[] nums, List<List<Integer>> ans, int depth) {
        int len = nums.length;

        // Reach the end of nums, add this solution to answer
        if (depth == len - 1) {
            List<Integer> solution = new ArrayList<>();

            for (int n : nums) {
                solution.add(n);
            }

            ans.add(solution);

            return;
        }

        // For depth = 0, this first slot could be len situations from num[0] to num[len-1]
        // Once the first slot determined, continue to go through rest elemennts

        // The reason why starts from depth instead of depth+1 is that element remaining at same
        // slot is also one situation
        for (int j = depth; j < len; j++) {
            swap(nums, depth, j);

            recurse(nums, ans, depth + 1);

            swap(nums, depth, j);
        }
    }

    static void swap(int[] nums, int x, int y) {
        int tmp = nums[x];
        nums[x] = nums[y];
        nums[y] = tmp;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-05 07:13:18

results matching ""

    No results matching ""