46. Permutations
来源:互联网 发布:免费通达信看盘软件 编辑:程序博客网 时间:2024/06/04 01:18
Given a collection of distinct 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], [3,2,1]]
刚开始天真地以为用迭代法可以做出来,可是真正做的时候发现很麻烦,其是这道题又是一道典型的回溯法,可以维护一个visited数组,用来记录哪些数字是已经被访问过的。
class Solution {public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> ans; vector<int> out; vector<int> visited(nums.size(), 0); permuteDFS(nums, 0, visited, out, ans); return ans; } void permuteDFS(vector<int>& nums, int level, vector<int>& visited, vector<int>& out, vector<vector<int>>& ans) { if (level == nums.size()) ans.push_back(out); else { for (int i = 0; i < nums.size(); i++) { if (visited[i] == 0) { visited[i] = 1; out.push_back(nums[i]); permuteDFS(nums, level + 1, visited, out, ans); out.pop_back(); visited[i] = 0; } } } } };
阅读全文
0 0
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- Python导入模块的几种姿势(常规导入, 相对导入, 可选导入, 本地导入)
- Python Imaging Library: ImageColor Module(图像颜色模块)
- 洪水攻击原理
- 关于动态导出Excel
- 【概率&数学期望】A Dangerous Maze LightOJ
- 46. Permutations
- Qt + OpenGL + 离屏渲染
- 2017/10/26学习心得
- Python编程:从入门到实践的动手试一试答案(第二章)
- 经典题目-如何测试一个一次性纸杯
- MarkDown标记语言入门
- PAT1009 说反话
- LinuxC编程预习
- 开发工程师必会的Linux命令