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 <= nums[i] <= 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;
    }
};
相关推荐
Yzzz-F3 小时前
Problem - 2205D - Codeforces
算法
智者知已应修善业4 小时前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
Halo_tjn4 小时前
Java Set集合相关知识点
java·开发语言·算法
生成论实验室4 小时前
《事件关系阴阳博弈动力学:识势应势之道》第四篇:降U动力学——认知确定度的自驱演化
人工智能·科技·神经网络·算法·架构
AI科技星5 小时前
全域数学·72分册:场计算机卷【乖乖数学】
算法·机器学习·数学建模·数据挖掘·量子计算
云泽8085 小时前
C++11 核心特性全解:列表初始化、右值引用与移动语义实战
开发语言·c++
科研前沿6 小时前
镜像孪生VS视频孪生核心技术产品核心优势
大数据·人工智能·算法·重构·空间计算
水蓝烟雨6 小时前
1931. 用三种不同颜色为网格涂色
算法·leetcode
AI进化营-智能译站6 小时前
ROS2 C++开发系列12-用多态与虚函数构建可扩展的ROS2机器人行为模块
开发语言·c++·ai·机器人
晨曦夜月6 小时前
map与unordered_map区别
算法·哈希算法