剑指 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[:])returnif len(path)>n:returnfor 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] = truedfs(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] = truedfs(u + 1, n, nums, &used, &path, &res)used[i] = falsepath.removeLast()}}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/34249.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

动手学深度学习:CNN和LeNet

前言 该篇文章记述从零如何实现CNN&#xff0c;以及LeNet对于之前数据集分类的提升效果。 从零实现卷积核 import torch def conv2d(X,k):h,wk.shapeYtorch.zeros((X.shape[0]-h1,X.shape[1]-w1))for i in range(Y.shape[0]):for j in range(Y.shape[1]):Y[i,j](X[i:ih,j:jw…

【开源代码解读】AI检索系统R1-Searcher通过强化学习RL激励大模型LLM的搜索能力

关于R1-Searcher的报告&#xff1a; 第一章&#xff1a;引言 - AI检索系统的技术演进与R1-Searcher的创新定位 1.1 信息检索技术的范式转移 在数字化时代爆发式增长的数据洪流中&#xff0c;信息检索系统正经历从传统关键词匹配到语义理解驱动的根本性变革。根据IDC的统计…

使用Node的http模块创建web服务,给客户端返回html页面时,css失效的根本原因(有助于理解http)

最近正在尝试使用node写后端&#xff0c;使用node创建http服务的时候&#xff0c;碰到了这样的一个问题&#xff1a; 这是我的源代码&#xff1a; import { createServer } from http import { join, dirname, extname } from path import { fileURLToPath } from url import…

JVM 2015/3/15

定义&#xff1a;Java Virtual Machine -java程序的运行环境&#xff08;java二进制字节码的运行环境&#xff09; 好处&#xff1a; 一次编写&#xff0c;到处运行 自动内存管理&#xff0c;垃圾回收 数组下标越界检测 多态 比较&#xff1a;jvm/jre/jdk 常见的JVM&…

IP风险度自检,互联网的安全“指南针”

IP地址就像我们的网络“身份证”&#xff0c;而IP风险度则是衡量这个“身份证”安全性的重要指标。它关乎着我们的隐私保护、账号安全以及网络体验&#xff0c;今天就让我们一起深入了解一下IP风险度。 什么是IP风险度 IP风险度是指一个IP地址可能暴露用户真实身份或被网络平台…

【鸿蒙】封装日志工具类 ohos.hilog打印日志

封装一个ohos.hilog打印日志 首先要了解hilog四大日志类型&#xff1a; info、debug、warm、error 方法中四个参数的作用 domain: number tag: string format: string ...args: any[ ] 实例&#xff1a; //普通的info日志&#xff0c;使用info方法来打印 //第一个参数 : 0x0…

走路碎步营养补充贴士

走路碎步&#xff0c;这种步伐不稳的现象&#xff0c;在日常生活中并不罕见&#xff0c;特别是对于一些老年人或身体较为虚弱的人来说&#xff0c;更是一种常见的行走状态。然而&#xff0c;这种现象可能不仅仅是肌肉或骨骼的问题&#xff0c;它还可能是身体在向我们发出营养缺…

Python软件和搭建运行环境

目录 一、Python安装全流程&#xff08;Windows/Mac/Linux&#xff09; 1. 下载官方安装包 2. 详细安装步骤&#xff08;以Windows为例&#xff09; 3. 环境变量配置&#xff08;Mac/Linux&#xff09; 二、虚拟环境管理&#xff08;关键&#xff01;&#xff09; 为什么需…

【蓝桥杯】省赛:神奇闹钟

思路 python做这题很简单&#xff0c;灵活用datetime库即可 code import os import sys# 请在此输入您的代码 import datetimestart datetime.datetime(1970,1,1,0,0,0) for _ in range(int(input())):ls input().split()end datetime.datetime.strptime(ls[0]ls[1],&quo…

RabbitMQ (Java)学习笔记

目录 一、概述 ①核心组件 ②工作原理 ③优势 ④应用场景 二、入门 1、docker 安装 MQ 2、Spring AMQP 3、代码实现 pom 依赖 配置RabbitMQ服务端信息 发送消息 接收消息 三、基础 work Queue 案例 消费者消息推送限制&#xff08;解决消息堆积方案之一&#…

HW基本的sql流量分析和wireshark 的基本使用

前言 HW初级的主要任务就是看监控&#xff08;流量&#xff09; 这个时候就需要我们 了解各种漏洞流量数据包的信息 还有就是我们守护的是内网环境 所以很多的攻击都是 sql注入 和 webshell上传 &#xff08;我们不管对面是怎么拿到网站的最高权限的 我们是需要指出它是…

camellia redis proxy v1.3.3对redis主从进行读写分离(非写死,自动识别故障转移)

1 概述 camellia-redis-proxy是一款高性能的redis代理&#xff08;https://github.com/netease-im/camellia&#xff09;&#xff0c;使用netty4开发&#xff0c;主要特性如下&#xff1a; 支持代理到redis-standalone、redis-sentinel、redis-cluster。支持其他proxy作为后端…

贪吃蛇小游戏-简单开发版

一、需求 本项目旨在开发一个经典的贪吃蛇游戏&#xff0c;用户可以通过键盘控制蛇的移动方向&#xff0c;让蛇吃掉随机出现在游戏区域内的食物&#xff0c;每吃掉一个食物&#xff0c;蛇的身体长度就会增加&#xff0c;同时得分也会相应提高。游戏结束的条件为蛇撞到游戏区域的…

使用 Docker 部署前端项目全攻略

文章目录 1. Docker 基础概念1.1 核心组件1.2 Docker 工作流程 2. 环境准备2.1 安装 Docker2.2 验证安装 3. 项目配置3.1 项目结构3.2 创建 Dockerfile 4. 构建与运行4.1 构建镜像4.2 运行容器4.3 访问应用 5. 使用 Docker Compose5.1 创建 docker-compose.yml5.2 启动服务5.3 …

接口自动化测试用例

Post接口自动化测试用例 Post方式的接口是上传接口&#xff0c;需要对接口头部进行封装&#xff0c;所以没有办法在浏览器下直接调用&#xff0c;但是可以用Curl命令的-d参数传递接口需要的参数。当然我们还以众筹网的登录接口为例&#xff0c;讲解post方式接口的自动化测试用…

使用WireShark解密https流量

概述 https协议是在http协议的基础上&#xff0c;使用TLS协议对http数据进行了加密&#xff0c;使得网络通信更加安全。一般情况下&#xff0c;使用WireShark抓取的https流量&#xff0c;数据都是加密的&#xff0c;无法直接查看。但是可以通过以下两种方法&#xff0c;解密抓…

阿里百炼Spring AI Alibaba

文章目录 学习链接阿里百炼创建api-key查看api调用示例示例pom.xmlAQuickStartMultiChatStreamChat Spring AI Alibaba简单示例pom.xmlapplication.ymlHelloworldControllerDashScopeChatModelController图解spring AI的结构 deepseekpom.xmlapplication.ymlDeepSeekChatClient…

【模拟算法】

目录 替换所有的问号 提莫攻击 Z 字形变换 外观数列 数青蛙&#xff08;较难&#xff09; 模拟算法&#xff1a;比葫芦画瓢。思路较简单&#xff0c;考察代码能力。 1. 模拟算法流程&#xff0c;一定要在演草纸上过一遍流程 2. 把流程转化为代码 替换所有的问号 1576. 替…

【Linux】进程(1)进程概念和进程状态

&#x1f31f;&#x1f31f;作者主页&#xff1a;ephemerals__ &#x1f31f;&#x1f31f;所属专栏&#xff1a;Linux 目录 前言 一、什么是进程 二、task_struct的内容 三、Linux下进程基本操作 四、父进程和子进程 1. 用fork函数创建子进程 五、进程状态 1. 三种重…

配置blender的python环境

在blender的脚本出输入&#xff1a; import sys print(sys.executable) 2. 通过上述命令我们得到blener的python版本&#xff0c;下面我们在conda配置一个同样版本的python环境。 conda create -n blenderpy python3.11.9找到blender安装路径下的python文件夹&#xff0c;将它…