多变量递归3-全排列问题

问题描述:给定一个没有重复数字的序列,返回其所有可能的全排列。

/**
*Given a sequence with no duplicate numbers, return all its possible permutations.
*given an array int arr[] = {1,2,3}
*output 
*[1,2,3]
*[1,3,2]
*[2,1,3]
*[2,3,1]
*[3,1,2]
*[3,2,1]
*/
import java.util.*;

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

    private void backtrack(int[] nums, List<Integer> path, boolean[] used, List<List<Integer>> res) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue;
            used[i] = true;
            path.add(nums[i]);
            backtrack(nums, path, used, res);
            used[i] = false;
            path.remove(path.size() - 1);
        }
    }
    
    public static void main(String[] args){
        int[] arr = {1,2,3,4};
        List<List<Integer>> res = permute(arr);
        for(List<Integer> aList : res){
            System.out.println(aList.toString());
        }
    }
}

 

posted on 2025-09-11 10:26  emalovecode  阅读(5)  评论(0)    收藏  举报