当前位置:网站首页>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));
}
}
}
};
边栏推荐
- Use baidu EasyDL implement factory workers smoking behavior recognition
- 字符串常用方法
- 记一个gorm初始化的坑
- Simple example of libcurl accessing url saved as file
- 60 Feature Engineering Operations: Using Custom Aggregate Functions【Favorites】
- [Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
- Redis 底层的数据结构
- 工程师如何对待开源
- Redis for distributed applications in Golang
- Rasa 3 x learning series - Rasa - 4873 dispatcher Issues. Utter_message study notes
猜你喜欢

The state status is displayed incorrectly after the openGauss switch

BI-SQL丨WHILE

【LeetCode Daily Question】——704. Binary Search

Win Go development kit installation configuration, GoLand configuration

一次SQL优化,数据库查询速度提升 60 倍

LeetCode Brushing Diary: 74. Searching 2D Matrix

FOFAHUB usage test

"NetEase Internship" Weekly Diary (2)

AWR分析报告问题求助:SQL如何可以从哪几个方面优化?

垃圾回收器CMS和G1
随机推荐
Reflex WMS Intermediate Series 7: What should I do if I want to cancel the picking of an HD that has finished picking but has not yet been loaded?
2022-08-01 安装mysql监控工具phhMyAdmin
Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案
2022 Henan Youth Training League Game (3)
Hash collisions and consistent hashing
¶ Backtop back to the top is not effective
永磁同步电机36问(三)——SVPWM代码实现
Pinduoduo leverages the consumer expo to promote the upgrading of domestic agricultural products brands and keep pace with international high-quality agricultural products
Win Go development kit installation configuration, GoLand configuration
Ask God to answer, how should this kind of sql be written?
Ringtone 1161. Maximum In-Layer Elements and
[LeetCode Daily Question] - 103. Zigzag Level Order Traversal of Binary Tree
GTK RGB图像绘制
【web】Understanding Cookie and Session Mechanism
Remember a pit for gorm initialization
"NetEase Internship" Weekly Diary (1)
NIO‘s Sword(牛客多校赛)
Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
TKU remembers a single-point QPS optimization (I wish ITEYE is finally back)
BI-SQL丨WHILE