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;
    }
};
相关推荐
音草28 分钟前
AVL 树详解:从概念到 C++ 实现
c++
凉茶钱38 分钟前
list:哨兵节点,const_iterator 和 const iterator的区别与迭代器失效
数据结构·c++·list
沫璃染墨1 小时前
从零入门计算机网络系列(六):TCP套接字编程实战——从listen监听到客户端与服务器通信
linux·服务器·c++·tcp/ip·计算机网络·tcp
Jsundoku1 小时前
第六章 机器学习 -- 支持向量机
算法·机器学习·支持向量机
?abc!1 小时前
(数组)448. 找到所有数组中消失的数字
算法
淡海水1 小时前
05-03-源码-Boehm GC分配与碎片管理
开发语言·算法·unity·c#·游戏引擎·gc
努力实干1 小时前
C++ 面向对象与工程架构
开发语言·c++·架构
代钦塔拉2 小时前
【C++/Qt 进阶】设计模式系列(6):桥接模式——把“两个独立变化的维度“拆开
c++·qt·设计模式
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C/C++考级:任意进制互转与大数多进制加法解析
c++·python·算法·bfs·信息学竞赛