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;
    }
};
相关推荐
Keep learning!7 分钟前
PCA主成分分析学习
学习·算法
朽棘不雕10 分钟前
c++中为什么new[]和delete[]要配对使用
c++
专注VB编程开发20年12 分钟前
CUDA实现随机切割算法,显卡多线程计算
算法·cuda
2301_7887705516 分钟前
OJ模拟4
算法
elseif12337 分钟前
出题团招人
c++
NAGNIP1 小时前
一文搞懂CNN经典架构-AlexNet!
人工智能·算法
不想写代码的星星1 小时前
SFINAE 的演进:从替换失败不是错误,到 Concepts 的优雅
c++
2401_878530212 小时前
自定义内存布局控制
开发语言·c++·算法
专注VB编程开发20年2 小时前
PNG、GIF透明游戏角色人物输出一张图片技巧,宽度高度读取
算法
CoderCodingNo2 小时前
【CSP】CSP-J 2025真题 | 异或和 luogu-P14359 (相当于GESP六级水平)
算法