2013.12.15 05:08
Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
Solution:
The STL library <algorithm> provides a function next_permutation(), which generates the next greater permutation for a sequence. If no greater permutation exists, the smallest permutation will be returned as the result.
I just called next_permutation() for n! times, thus the time complexity is O(n * n!). next_permutation() requires O(n) time on average. Space complexity is O(n).
Accepted code:
1 // 1AC, next_permutation is handy~ 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 vector<vector<int> > permute(vector<int> &num) { 8 // IMPORTANT: Please reset any member data you declared, as 9 // the same Solution instance will be reused for each test case. 10 for(int i = 0; i < result.size(); ++i){ 11 result[i].clear(); 12 } 13 result.clear(); 14 15 int i; 16 int n = num.size(); 17 int nn = 1; 18 19 for(i = 1; i <= n; ++i){ 20 nn *= i; 21 } 22 23 for(i = 0; i < nn; ++i){ 24 result.push_back(vector<int>(num)); 25 next_permutation(num.begin(), num.end()); 26 } 27 28 return result; 29 } 30 private: 31 vector<vector<int>> result; 32 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)