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;
    }
};
相关推荐
Emberone4 分钟前
排序:万物皆有序
算法·排序算法
其实秋天的枫6 分钟前
2025年12月英语六级真题及答案解析完整版(第一、二、三套全PDF)
经验分享·算法
2401_8747325312 分钟前
C++并发编程中的死锁避免
开发语言·c++·算法
2301_7923082514 分钟前
C++编译期数学计算
开发语言·c++·算法
hetao173383714 分钟前
2025-03-13~22 hetao1733837 的刷题记录
c++·算法
sqyno1sky26 分钟前
C++中的契约编程
开发语言·c++·算法
优化控制仿真模型38 分钟前
2026年最新驾考科目一考试题库2309道全。电子版pdf
经验分享·算法·pdf
qq_3349031540 分钟前
嵌入式C++驱动开发
开发语言·c++·算法
阿贵---1 小时前
C++代码规范化工具
开发语言·c++·算法
暮冬-  Gentle°1 小时前
自定义内存检测工具
开发语言·c++·算法