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;
    }
};
相关推荐
满天星83035771 分钟前
【算法】最长递增子序列(三种解法)
算法
hold?fish:palm5 分钟前
kv存储主从复制的设计与实现
c++·redis·后端
啦啦啦啦啦zzzz41 分钟前
算法:贪心算法
c++·算法·leetcode·贪心算法
charlie1145141911 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
日拱一卒——功不唐捐2 小时前
红黑树删除(C语言)
c语言·数据结构
清泓y2 小时前
RAG 技术
算法·ai
不如语冰2 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
阿慧今天瘦了嘛2 小时前
计算机组成原理概述:从硬件到软件的桥梁
计算机网络·算法
JetComXCpp3 小时前
给 Win32 窗口加上毛玻璃效果——纯 D3D11 实现,零依赖
c++
Angle.寻梦3 小时前
数据结构--链表
数据结构·链表