当前位置:网站首页>51. 数字排列
51. 数字排列
2022-08-02 02:20:00 【Hunter_Kevin】
51. 数字排列
输入一组数字(可能包含重复数字),输出其所有的排列方式。
数据范围
输入数组长度 [0,6]。
样例
输入:[1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
代码:

如果数组数字可能有重复,则先对数组元素排序,规定相等元素的相对的先后顺序即可
class Solution {
public:
vector<vector<int>> res;//返回的结果
vector<int> path;//存储当前的一次序列
vector<vector<int>> permutation(vector<int>& nums) {
path.resize(nums.size());//重置大小
sort(nums.begin(), nums.end());//排序
dfs(nums,0,0,0);//从0开始放,记录上一个元素放的位置
return res;
}
// cur 当前需要插入的位置
// start 重复字符这次可以开始的位置
// 用二进制数2^(n-1)标记是否已经使用过
void dfs(vector<int>& nums, int cur, int start, int state){
if(cur >= nums.size()){
res.push_back(path);
return;
}
if(cur == 0 || nums[cur] != nums[cur-1]) start = 0;//可以从下标为0开始插入
for(int i = start; i < nums.size(); i++){
if(!(state>>i&1)){
//如果第i位为0,即没有使用过
// state += 1 << i;//如果放在这里,会影响到下一次循环时state的值
path[i] = nums[cur];
dfs(nums,cur+1,i+1, state + (1 << i));
}
}
}
};
边栏推荐
- PHP uses PHPRedis and Predis
- Scheduled tasks for distributed applications in Golang
- Safety (2)
- 一次SQL优化,数据库查询速度提升 60 倍
- Fundamentals of Cryptography: X.690 and Corresponding BER CER DER Encodings
- PHP live source code to achieve simple barrage effect related code
- [ORB_SLAM2] SetPose, UpdatePoseMatrices
- The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
- Use DBeaver for mysql data backup and recovery
- AWR analysis report questions for help: How can SQL be optimized from what aspects?
猜你喜欢

The principle and code implementation of intelligent follower robot in the actual combat of innovative projects

【LeetCode每日一题】——704.二分查找

数据链路层的数据传输

FOFAHUB usage test

Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!

2022-08-01 mysql/stoonedb慢SQL-Q18分析

Data transfer at the data link layer

LeetCode刷题日记:LCP 03.机器人大冒险

Nanoprobes免疫测定丨FluoroNanogold试剂免疫染色方案

The underlying data structure of Redis
随机推荐
接口测试神器Apifox究竟有多香?
Outsourcing worked for three years, it was abolished...
2022-08-01 mysql/stoonedb slow SQL-Q18 analysis
十字光标太小怎么调节、CAD梦想画图算量技巧
【web】Understanding Cookie and Session Mechanism
用位运算为你的程序加速
数据链路层的数据传输
【web】理解 Cookie 和 Session 机制
Redis Subscription and Redis Stream
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
volatile原理解析
LeetCode brushing diary: 53, the largest sub-array and
Check if IP or port is blocked
ALCCIKERS Shane 20191114
2022-08-01 反思
【LeetCode每日一题】——654.最大二叉树
【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
Service discovery of kubernetes
bool框架::PosInGrid (const简历:关键点kp, int &posX, int诗句)
Constructor instance method inheritance of typescript37-class (extends)