LeetCode46. Permutations

文章目录

一、题目

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1:

Input: nums = 1,2,3

Output: \[1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1]

Example 2:

Input: nums = 0,1

Output: \[0,1,1,0]

Example 3:

Input: nums = 1

Output: \[1]

Constraints:

1 <= nums.length <= 6

-10 <= numsi <= 10

All the integers of nums are unique.

二、题解

cpp 复制代码
class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;
    void backtracking(vector<int>& nums,vector<int>& used){
        if(path.size() == nums.size()){
            res.push_back(path);
            return;
        }
        for(int i = 0;i < nums.size();i++){
            if(used[i] == 1) continue;
            used[i] = 1;
            path.push_back(nums[i]);
            backtracking(nums,used);
            path.pop_back();
            used[i] = 0;
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        int n = nums.size();
        vector<int> used(n,0);
        backtracking(nums,used);
        return res;
    }
};
相关推荐
wuyk5555 分钟前
13.堆排序:基于完全二叉树的高效排序算法一、什么是堆排序?
开发语言·算法·排序算法
光电笑映9 分钟前
Linux 线程编程:从进程、分页到线程控制与封装
linux·运维·服务器·c++
qinzechen9 分钟前
本周科技行业热点汇总·2026第36周(2026年8月31日-9月6日)
c++·科技·算法
白狐_79824 分钟前
408 数据结构|红黑树 vs AVL:高频考点、易错判断与可能出题方式
数据结构·算法
aqiu11111129 分钟前
【C++ 代码分析与重构】常见 DFS 逻辑错误解析与修正
c++·重构·深度优先
zuozong_30 分钟前
C++类与对象
开发语言·c++·算法
hansang_IR34 分钟前
【代码】分层最短路模板
c++·算法·最短路
暖焰核心34 分钟前
C++模板进阶——特化全解
javascript·c++·jquery
励志不掉头发的内向程序员38 分钟前
【LibreCAD 2D架构】从两个坐标到图形实体:RS_ActionDrawLine如何创建RS_Line
开发语言·c++·qt·学习·系统架构
啊阿狸不会拉杆42 分钟前
《计算机网络-自顶向下方法》5.2 路由选择算法 读书笔记
计算机网络·算法·路由