当前位置:网站首页>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));
}
}
}
};
边栏推荐
- NIO's Sword
- The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
- Hiring a WordPress Developer: 4 Practical Ways
- 【LeetCode每日一题】——704.二分查找
- 2022-08-01 Install mysql monitoring tool phhMyAdmin
- 拼多多借力消博会推动国内农产品品牌升级 看齐国际精品农货
- 2022-08-01 mysql/stoonedb慢SQL-Q18分析
- Golang分布式应用之定时任务
- Remember a pit for gorm initialization
- 【LeetCode每日一题】——654.最大二叉树
猜你喜欢
随机推荐
【LeetCode每日一题】——704.二分查找
使用DBeaver进行mysql数据备份与恢复
2022-07-30 mysql8 executes slow SQL-Q17 analysis
MySQL - CRUD operations
Software testing Interface automation testing Pytest framework encapsulates requests library Encapsulates unified request and multiple base path processing Interface association encapsulation Test cas
Handwriting a blogging platform ~ Day 3
力扣、752-打开转盘锁
2022-08-01 安装mysql监控工具phhMyAdmin
Golang分布式应用之定时任务
【web】Understanding Cookie and Session Mechanism
【Unity入门计划】2D Game Kit:初步了解2D游戏组成
LeetCode brushing diary: 33. Search and rotate sorted array
Coding Experience Talk
Electronic Manufacturing Warehouse Barcode Management System Solution
局部敏感哈希:如何在常数时间内搜索Embedding最近邻
Redis 底层的数据结构
swift project, sqlcipher3 -> 4, cannot open legacy database is there a way to fix it
oracle query scan full table and walk index
How engineers treat open source
接口测试神器Apifox究竟有多香?









