Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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]
]

做了几个 backtrack 类的题目了, 对这个题还是没思路.

我目前的经验, backtrack 题目,要确定下面三个重要部件:

  1. 把 temp 压入 res 的条件!
    • 通常这个样 if (condition) {res.push_back(temp);}
  2. 怎样生成符合题意的 temp!
    • 通常这个样 else{for(int i=var; i<A.size(); i++){temp.push_back(A[i]); backtrack(params); temp.pop_back();}}
  3. backtrack 函数参数列表.

上面三点考虑时似乎没个先后顺序,好难哦.

人家想法,自个代码(被教育后的结果):

vector<vector<int>> permute(vector<int>& A) {
	vector < vector<int> > res;
	vector<int> temp;
	backtrack(A, res, temp);
	return res;
}

void backtrack(vector<int>& A, vector<vector<int> >& res, vector<int> temp) {
	// 重要部件
	if (temp.size() == A.size()) {
		res.push_back(temp); // 1. 啥时候 把 temp 压入 res, 很重要!!
		return;
	} else {
		// 2. 如何生成 temp 很重要!!
		for (int i = 0; i < A.size(); i++) {
			// contain A[i] is true
			if (find(temp.begin(), temp.end(), A[i]) != temp.end())
				continue;

			temp.push_back(A[i]);
			backtrack(A, res, temp);
			temp.pop_back();
		}
		return;
	}
}
posted on 2017-09-11 16:24  英雄与侠义的化身  阅读(144)  评论(0编辑  收藏  举报