当前位置:网站首页>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));
}
}
}
};
边栏推荐
- Ringtone 1161. Maximum In-Layer Elements and
- BioVendor人俱乐部细胞蛋白(CC16)Elisa试剂盒研究领域
- bool框架::PosInGrid (const简历:关键点kp, int &posX, int诗句)
- 数据链路层的数据传输
- Handwriting a blogging platform ~ Day 3
- PHP live source code to achieve simple barrage effect related code
- 软件测试 接口自动化测试 pytest框架封装 requests库 封装统一请求和多个基础路径处理 接口关联封装 测试用例写在yaml文件中 数据热加载(动态参数) 断言
- PHP uses PHPRedis and Predis
- Handwriting a blogging platform ~ the first day
- libcurl访问url保存为文件的简单示例
猜你喜欢

nacos startup error, the database has been configured, stand-alone startup

Safety (2)

"NetEase Internship" Weekly Diary (2)

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

Talking about the "horizontal, vertical and vertical" development trend of domestic ERP

From 2023 onwards, these regions will be able to obtain a certificate with a score lower than 45 in the soft examination.

MySQL optimization strategy

BI-SQL丨WHILE

十字光标太小怎么调节、CAD梦想画图算量技巧

Install mysql using docker
随机推荐
Centos7 install postgresql and enable remote access
leetcode/字符串中的变位词-s1字符串的某个排列是s2的子串
Can Youxuan database import wrongly be restored?
LeetCode刷题日记:LCP 03.机器人大冒险
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
Scheduled tasks for distributed applications in Golang
项目后台技术Express
A good book for newcomers to the workplace
Effects of Scraping and Aggregation
2022-08-01 mysql/stoonedb慢SQL-Q18分析
LeetCode刷题日记:34、 在排序数组中查找元素的第一个和最后一个位置
Golang分布式应用之定时任务
[LeetCode Daily Question]——654. The largest binary tree
Electronic Manufacturing Warehouse Barcode Management System Solution
2022年NPDP考完多久出成绩?怎么查询?
接口测试神器Apifox究竟有多香?
记一次gorm事务及调试解决mysql死锁
PHP live source code to achieve simple barrage effect related code
[LeetCode Daily Question] - 103. Zigzag Level Order Traversal of Binary Tree
Rasa 3 x learning series - Rasa - 4873 dispatcher Issues. Utter_message study notes