LeetCode_Permutations
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] |
找全排列,DFS的一般应用
class Solution { public: void DFS(vector<int> &num, int size,vector<int> temp) { if(size == n){ result.push_back(temp); return ; } for(int i = 0; i< n; i++) { if(flag[i] == false) { temp[size] = num[i]; flag[i] = true; DFS(num, size+1, temp); flag[i] = false; } } } vector<vector<int> > permute(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function n = num.size(); result.clear(); flag.resize(n,false); if(n == 0) return result; vector<int> temp(n,0) ; DFS(num,0,temp); return result ; } private : int n; vector<bool> flag; vector<vector<int>> result; };
--------------------------------------------------------------------天道酬勤!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步