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;
    }
};
相关推荐
ysa0510303 小时前
【板子】拓扑排序
c++·算法·图论·板子
某不知名網友4 小时前
项目:轻量级搜索引擎
c++
算法备案代理4 小时前
宽带自动连接保姆级教程
算法
罗超驿4 小时前
双指针算法详解:从入门到精通(Java版)
算法·leetcode·职场和发展
m0_377062924 小时前
电池电量计库伦算法计算公式
算法
patrickpdx4 小时前
高联预赛中的高斯函数问题
算法
tkevinjd4 小时前
力扣300-最长递增子序列
算法·leetcode·职场和发展·动态规划·贪心
A_humble_scholar5 小时前
Linux(十七)深入多线程编程:同步原语与实战指南
linux·运维·c++
小李飞刀李寻欢5 小时前
DeepSeek V3 版本模型结构分析
算法·大模型·deepseek
某不知名網友6 小时前
C++ 七大排序算法完整讲解
java·算法·排序算法