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;
    }
};
相关推荐
Jeff-Nolan8 小时前
数据结构(c++版):邻接表的实现
数据结构·链表
千弥霜8 小时前
codeforces1914 C~F
c语言·算法
wyiyiyi9 小时前
【数据结构+算法】进栈顺序推算、卡特兰数与逆波兰表达式
汇编·数据结构·笔记·算法
天若有情6739 小时前
Multi-Stride Predictive RNG:革命性的可控随机数生成算法
算法·算法设计·c++编程·随机数生成·msp-rng·魔术算法
guguhaohao9 小时前
map和set,咕咕咕!
数据结构·c++
C_Liu_9 小时前
14:C++:二叉搜索树
算法
CC-NX9 小时前
32位汇编:实验9分支程序结构使用
汇编·算法·win32·分支结构
Larry_Yanan9 小时前
QML学习笔记(五十二)QML与C++交互:数据转换——时间和日期
开发语言·c++·笔记·qt·学习·ui·交互
万岳科技系统开发9 小时前
外卖小程序中的高并发处理:如何应对大流量订单的挑战
算法·小程序·开源
TL滕9 小时前
从0开始学算法——第二天(时间、空间复杂度)
数据结构·笔记·学习·算法