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;
    }
};
相关推荐
写后端的胖头鱼6 小时前
一文详解B+树原理(附场景+示例)
数据结构·b树
怕浪猫8 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
无线通信科研笔记8 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_39 小时前
二叉树の递归遍历
算法
All for pursuit.9 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉10 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
WL学习笔记11 小时前
日期类(C++)
开发语言·c++·日期类实现
H.莓飛11 小时前
【C++】命名空间、缺省参数、函数重载与引用
linux·开发语言·c++·visual studio
一只小小的芙厨12 小时前
【线性DP】
学习·算法·动态规划
xxwl58512 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构