当前位置: 首页 > news >正文

剑指 Offer II 083. 没有重复元素集合的全排列


comments: true
edit_url: https://github.com/doocs/leetcode/edit/main/lcof2/%E5%89%91%E6%8C%87%20Offer%20II%20083.%20%E6%B2%A1%E6%9C%89%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0%E9%9B%86%E5%90%88%E7%9A%84%E5%85%A8%E6%8E%92%E5%88%97/README.md

剑指 Offer II 083. 没有重复元素集合的全排列

题目描述

给定一个不含重复数字的整数数组 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 中的所有整数 互不相同

 

注意:本题与主站 46 题相同:https://leetcode.cn/problems/permutations/ 

解法

方法一

Python3
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        n=len(nums)
        res=[]
        path=[]

        def dfs(i):
            if len(path)==n:
                res.append(path[:])
                return
            if len(path)>n:
                return

            for j in range(n):
                if nums[j] in path:continue  # 也可以空间换时间used[j]
                path.append(nums[j])
                dfs(j)
                path.pop()
        dfs(0)
        return res
Java
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        int n = nums.length;
        boolean[] used = new boolean[n];
        dfs(0, n, nums, used, path, res);
        return res;
    }

    private void dfs(
        int u, int n, int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) {
        if (u == n) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < n; ++i) {
            if (!used[i]) {
                path.add(nums[i]);
                used[i] = true;
                dfs(u + 1, n, nums, used, path, res);
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}
C++
class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        int n = nums.size();
        vector<vector<int>> res;
        vector<int> path(n, 0);
        vector<bool> used(n, false);
        dfs(0, n, nums, used, path, res);
        return res;
    }

    void dfs(int u, int n, vector<int>& nums, vector<bool>& used, vector<int>& path, vector<vector<int>>& res) {
        if (u == n) {
            res.emplace_back(path);
            return;
        }
        for (int i = 0; i < n; ++i) {
            if (!used[i]) {
                path[u] = nums[i];
                used[i] = true;
                dfs(u + 1, n, nums, used, path, res);
                used[i] = false;
            }
        }
    }
};
Go
func permute(nums []int) [][]int {
	n := len(nums)
	res := make([][]int, 0)
	path := make([]int, n)
	used := make([]bool, n)
	dfs(0, n, nums, used, path, &res)
	return res
}

func dfs(u, n int, nums []int, used []bool, path []int, res *[][]int) {
	if u == n {
		t := make([]int, n)
		copy(t, path)
		*res = append(*res, t)
		return
	}
	for i := 0; i < n; i++ {
		if !used[i] {
			path[u] = nums[i]
			used[i] = true
			dfs(u+1, n, nums, used, path, res)
			used[i] = false
		}
	}
}
JavaScript
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function (nums) {
    const n = nums.length;
    let res = [];
    let path = [];
    let used = new Array(n).fill(false);
    dfs(0, n, nums, used, path, res);
    return res;
};

function dfs(u, n, nums, used, path, res) {
    if (u == n) {
        res.push(path.slice());
        return;
    }
    for (let i = 0; i < n; ++i) {
        if (!used[i]) {
            path.push(nums[i]);
            used[i] = true;
            dfs(u + 1, n, nums, used, path, res);
            used[i] = false;
            path.pop();
        }
    }
}
C#
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public IList<IList<int>> Permute(int[] nums) {
        var results = new List<IList<int>>();
        var temp = new List<int>();
        var visited = new bool[nums.Length];
        Search(nums, visited, temp, results);
        return results;
    }

    private void Search(int[] nums, bool[] visited, IList<int> temp, IList<IList<int>> results)
    {
        int count = 0;
        for (var i = 0; i < nums.Length; ++i)
        {
            if (visited[i]) continue;
            ++count;
            temp.Add(nums[i]);
            visited[i] = true;
            Search(nums, visited, temp, results);
            temp.RemoveAt(temp.Count - 1);
            visited[i] = false;
        }
        if (count == 0 && temp.Any())
        {
            results.Add(new List<int>(temp));
        }
    }
}
Swift
class Solution {
    func permute(_ nums: [Int]) -> [[Int]] {
        var res = [[Int]]()
        var path = [Int]()
        var used = [Bool](repeating: false, count: nums.count)
        dfs(0, nums.count, nums, &used, &path, &res)
        return res
    }

    private func dfs(
        _ u: Int, _ n: Int, _ nums: [Int], _ used: inout [Bool], _ path: inout [Int], _ res: inout [[Int]]
    ) {
        if u == n {
            res.append(path)
            return
        }
        for i in 0..<n {
            if !used[i] {
                path.append(nums[i])
                used[i] = true
                dfs(u + 1, n, nums, &used, &path, &res)
                used[i] = false
                path.removeLast()
            }
        }
    }
}

相关文章:

  • 支持本地部署人力资源系统:6款工具评测精选
  • golang time包和日期函数
  • ​​​​​​​大语言模型安全风险分析及相关解决方案
  • 蓝桥杯嵌入式赛道复习笔记1(led点亮)
  • Python实现限流算法
  • 使用-v选项查看编译器详细搜索路径(g++示例)g++ -v -c main.cpp 发现自定义路径没有被包含怎么办
  • 如何用Deepseek制作流程图?
  • 数据结构---堆栈和列
  • 77.HarmonyOS NEXT ImageViewerView 组件深度剖析: Swiper容器与懒加载深度解析
  • 智慧加油站小程序数据库设计文档
  • Redis 的应用场景
  • 提升HDFS存储和读取效率
  • Json实现深拷贝的缺点
  • 2.5 python接口编程
  • Java File 类详解
  • Wireshark 抓包全解析:从数据捕获到报文分析
  • 2024年12月CCF-GESP编程能力等级认证C++编程二级真题解析
  • 深入探索人工智能(AI):分类、应用与案例分析
  • 基于模态特定因子的高效低秩多模态融合方法解析
  • 基于Python的天气预报数据可视化分析系统-Flask+html
  • 8000余万元黄金投入研发后“不知去向”,咋回事?
  • 上影节公布今年IMAX片单:暗涌、重生与感官的史诗
  • 证监会副主席李明:支持符合条件的外资机构申请新业务、设立新产品
  • 中国田径巡回赛西安站完赛:男子跳远石雨豪夺冠,女子跳高刘肼毅折桂
  • 江苏疾控:下设部门无“病毒研究所”,常荣山非本单位工作人员
  • 上海高院与上海妇联签协议,建立反家暴常态化联动协作机制