赞
踩
题目要求
思路
1.递归,如果num和n的元素个数一样就可以插入res中了,这个作为递归的结束条件
2.因为这个题是属于排列,并非组合,两者的区别是排列需要把之前插入的元素在回退会去,而组合不需要,因此会存在一个pop_back()的操作。
3.特殊情况的处理,如果这个元素已经在n中插入过,就需要跳过该元素,对应的是题目中的不能重复,因为这里需要跳过的是最外面的for循环,因此,只能通过flag建立标记,而无法通过continue直接跳过,continue只能跳过用于做判断的内循环。
代码实现
class Solution { public: vector<vector<int>> res; vector<vector<int> > permute(vector<int>& num) { vector<int> n; per(num, n); return res; } void per(vector<int>& num, vector<int>& n) { if(num.size() == n.size()) { res.push_back(n); return; } for(int i = 0; i < num.size(); i++) { bool flag = false; for(int j = 0; j < n.size(); j++) { if(num[i] == n[j]) flag = true; } if(flag) continue; n.push_back(num[i]); per(num, n); n.pop_back(); } } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。