当前位置:网站首页>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));
}
}
}
};
边栏推荐
- LeetCode刷题日记:153、寻找旋转排序数组中的最小值
- Check if IP or port is blocked
- 2022 NPDP take an examination of how the results?How to query?
- 字符串常用方法
- The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
- 2022-08-01 Install mysql monitoring tool phhMyAdmin
- 软件测试 接口自动化测试 pytest框架封装 requests库 封装统一请求和多个基础路径处理 接口关联封装 测试用例写在yaml文件中 数据热加载(动态参数) 断言
- Speed up your programs with bitwise operations
- Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation
- Talking about the "horizontal, vertical and vertical" development trend of domestic ERP
猜你喜欢
FOFAHUB使用测试
From 2023 onwards, these regions will be able to obtain a certificate with a score lower than 45 in the soft examination.
Service discovery of kubernetes
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
记一次gorm事务及调试解决mysql死锁
Use baidu EasyDL implement factory workers smoking behavior recognition
[LeetCode Daily Question] - 103. Zigzag Level Order Traversal of Binary Tree
LeetCode Brushing Diary: 74. Searching 2D Matrix
Chopper webshell feature analysis
使用docker安装mysql
随机推荐
Unable to log in to the Westward Journey
swift project, sqlcipher3 -> 4, cannot open legacy database is there a way to fix it
垃圾回收器CMS和G1
LeetCode刷题日记:LCP 03.机器人大冒险
接口测试神器Apifox究竟有多香?
Redis Subscription and Redis Stream
2022-08-01 mysql/stoonedb慢SQL-Q18分析
BioVendor Human Club Cellular Protein (CC16) Elisa Kit Research Fields
记一次gorm事务及调试解决mysql死锁
Garbage Collector CMS and G1
The state status is displayed incorrectly after the openGauss switch
Golang分布式应用之定时任务
LeetCode 213. Robbery II (2022.08.01)
Coding Experience Talk
2022 NPDP take an examination of how the results?How to query?
2022年NPDP考完多久出成绩?怎么查询?
ALCCIKERS Shane 20191114
数据链路层的数据传输
Chengdu openGauss user group recruit!
Analysis of volatile principle