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;
    }
};
相关推荐
阿猿收手吧!1 分钟前
【C++】brpc与grpc对比
开发语言·c++
oioihoii6 分钟前
C++虚函数表与多重继承内存布局深度剖析
java·jvm·c++
会员果汁15 分钟前
算法-拓扑排序-C
c语言·开发语言·算法
BestOrNothing_201519 分钟前
C++ 内存泄漏的“真实成本”: 内存单位换算、堆分配开销与工程级判断
c++·内存管理·内存泄漏·堆内存·raii·内存换算·异常安全
YGGP25 分钟前
【Golang】LeetCode 72. 编辑距离
算法·leetcode
YGGP33 分钟前
【Golang】LeetCode 62. 不同路径
算法·leetcode
资生算法程序员_畅想家_剑魔39 分钟前
算法-回溯-14
java·开发语言·算法
致Great1 小时前
大模型对齐核心技术:从第一性原理完整推导 PPO 算法!
人工智能·算法·大模型·agent·智能体
_w_z_j_1 小时前
二叉树的右视图(BFS或DFS)
算法·深度优先·宽度优先
cyyt1 小时前
深度学习周报(12.22~12.28)
人工智能·算法·机器学习