程序员社区

LeetCode-46-全排列

46. 全排列

难度中等1338收藏分享切换为英文接收动态反馈

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:

输入:nums = [0,1]
输出:[[0,1],[1,0]]

示例 3:

输入:nums = [1]
输出:[[1]]

提示:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums 中的所有整数 互不相同

  • 暴力递归
class Solution {
   public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        HashSet<Integer> rest = new HashSet<>();
        for (int num : nums) {
            rest.add(num);
        }
        ArrayList<Integer> path = new ArrayList<>();
        f(rest, path, ans);
        return ans;
    }

    // rest中有剩余数字,已经选过的数字不在rest中,选过的数字在path里
    //走到最会的答案收集在ans中
    public static void f(HashSet<Integer> rest, ArrayList<Integer> path, List<List<Integer>> ans) {
        if (rest.isEmpty()) {//已经选完,收集答案
            ans.add(path);
        } else {
            for (int num : rest) {
                ArrayList<Integer> curPath = new ArrayList<>(path);
                curPath.add(num);
                HashSet<Integer> clone = cloneExceptNum(rest, num);
                f(clone, curPath, ans);
            }
        }
    }

    public static HashSet<Integer> cloneExceptNum(HashSet<Integer> rest, int num) {
        HashSet<Integer> clone = new HashSet<>(rest);
        clone.remove(num);
        return clone;
    }
}
LeetCode-46-全排列插图
image-20210511090408111
LeetCode-46-全排列插图1
image-20210511092746287
LeetCode-46-全排列插图2
image-20210511093045331
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        process(nums, 0, ans);
        return ans;
    }

    public static void process(int[] nums, int index, List<List<Integer>> ans) {
        if (index == nums.length) {//收集最后的答案
            ArrayList<Integer> cur = new ArrayList<>();
            for (int num : nums) {
                cur.add(num);
            }
            ans.add(cur);
        } else {
            for (int j = index; j < nums.length; j++) {
                swap(nums, index, j);
                process(nums, index + 1, ans);
                swap(nums, index, j);
            }
        }
    }

    public static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
LeetCode-46-全排列插图3
image-20210511090706649
赞(0) 打赏
未经允许不得转载:IDEA激活码 » LeetCode-46-全排列

一个分享Java & Python知识的社区