【LeetCode从零单刷】Permutations
来源:互联网 发布:elementary os ubuntu 编辑:程序博客网 时间:2024/06/13 01:36
题目:
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]
.
解答:
回溯法(剪枝法)。技巧以及注意事项已经在《【LeetCode从零单刷】Generate Parentheses》中说明:
- 每次只递归一步,绝不多一步。这个和递归法是相同的道理;
- 只有最底层负责存入结果,存入一个脱离于函数的全局内存;
- 层与层之间,不再传递数据(因为回溯的答案不止一个,每层处理去重没必要,交给最底层存入)。但是每层必须有 return 返回上层,否则函数无法终止),return 一个空值
class Solution {public: vector<vector<int>> ret; void gao(vector<int> rest, vector<int> ans) { if (rest.size() == 0) { ret.push_back(ans); return; } else { for(vector<int>::iterator it=rest.begin(); it != rest.end(); it++) { vector<int> tmp_rest = rest; vector<int> tmp_ans = ans; ans.push_back(*it); rest.erase(it); gao(rest, ans); rest = tmp_rest; ans = tmp_ans; } return; } } vector<vector<int>> permute(vector<int>& nums) { ret.clear(); vector<int> tmp; tmp.clear(); gao(nums, tmp); return ret; }};
这里还需要另外注意一些事项:
- 迭代器是一种指针,取值时需要加上 *,即 (*it);
- vector 容器中删除某个值,需要利用到 vector.erase( 迭代器 )。同时注意,是直接修改原本的 vector 容器。所以需要保存修改之前的容器;
- 迭代器只能适用于原本的容器,即使新的容器复制了老的容器,迭代器也无法适用于新容器
0 0
- 【LeetCode从零单刷】Permutations
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- 【leetcode】Permutations
- MS08-067漏洞重现
- 数据库概论学习笔记------什么是存储引擎
- C#转换人民币大写金额
- The method getJspApplicationContext(ServletContext) is undefined for&nb
- Android智力火柴游戏源码项目
- 【LeetCode从零单刷】Permutations
- springmvc + freemarker 开发环境 缓存设置
- 弹出提示框插件
- cin.clear()、cin.sync()和cin.ignor()的用法
- iOS数组内容不重复
- linux v4L2 初步框架
- java 解决simpledateformat线程安全问题
- maven学习
- Unix:用户自定义信号-SIGUSR1和SIGUSR2