[Leetcode 53] 46 Permutations
Problem:
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]
.
Analysis:
It's a backtracking problem. In order to make sure that we don't access the same element multiple times, we use an extra tag array to keep the access information. Only those with tag value equals 0 will be chose as candidates.
Code:
1 class Solution { 2 public: 3 vector<vector<int> > res; 4 5 vector<vector<int> > permute(vector<int> &num) { 6 // Start typing your C/C++ solution below 7 // DO NOT write int main() function 8 if (num.size() == 0) return res; 9 10 res.clear(); 11 vector<int> r; 12 vector<int> tag(num.size(), 0); 13 bc(r, tag, num); 14 15 return res; 16 } 17 18 void bc(vector<int> path, vector<int> &tag, vector<int> &num) { 19 if (path.size() == num.size()) { 20 res.push_back(path); 21 return ; 22 } 23 24 for (int i=0; i<num.size(); i++) { 25 if (tag[i] == 0) { 26 path.push_back(num[i]); 27 tag[i] = 1; 28 bc(path, tag, num); 29 tag[i] = 0; 30 path.pop_back(); 31 } 32 } 33 34 return ; 35 } 36 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步