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;
    }
};
相关推荐
Liaiyang667 分钟前
空圈容错视角 · 多维切面篇:我们生活的世界,不止三维
人工智能·算法·系统架构·前沿技术·哲学·认知科学
闻缺陷则喜何志丹18 分钟前
【环】P6709 [CCC 2020] Swapping Seats 环|普及+
算法·洛谷·环
开开心心就好23 分钟前
打印机卡住打不了?一键清理卡死打印队列
服务器·开发语言·算法·pdf·ocr·idea·visual studio code
格物致胜工业数智技术26 分钟前
锂电纠偏测量那些坑,明治ETD-0612激光纠偏传感器怎么填?
人工智能·算法
垆边人似月.30 分钟前
带权区间调度,优先级可负
算法
重生之小比特31 分钟前
【算法拾光】双指针|三数之和 + 四数之和
算法
David猪大卫31 分钟前
【C++修炼】STL容器—模板进阶:非类型模板参数、模板特化、模板分离编译
c语言·开发语言·c++·经验分享·笔记·学习·面试
我爱工作&工作love我34 分钟前
P14359 [CSP-J 2025] 异或和
算法
茉莉玫瑰花茶34 分钟前
GO [ 数据格式 ]
服务器·网络·算法·golang
小poop36 分钟前
高级排序算法与性能对比——归并、非比较排序及总结
数据结构·算法·排序算法