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;
    }
};
相关推荐
坤坤子吖5 分钟前
算法学习——单调队列
开发语言·c++·笔记·学习·算法
杜 硕36 分钟前
从零开始的C++生活——第六讲——01
开发语言·c++·生活
Js.Tx1 小时前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
Risehuxyc3 小时前
C++(VS2026)使用Ncap库的配置
c++
秋天的怀念_David3 小时前
算法一千零一夜 · 作品相关:版权与致谢声明
程序人生·算法·学习方法
图灵-M3 小时前
【数据结构】静态 & 动态顺序表
c语言·数据结构·笔记
4ever.ov03 小时前
精学C++第一站 从命名空间到引用:C++入门核心语法全梳理(13000字长文)
开发语言·c++·clion
揽星河..3 小时前
【C语言】数组
c语言·开发语言·算法
careathers3 小时前
【数据结构】基于比较的排序算法 - 选择排序
数据结构·算法·排序算法
听风若依4 小时前
C++模板初阶
c++·算法