Permutations
2014-12-22 18:24 李涛的技术博客 阅读(279) 评论(0) 编辑 收藏 举报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], [3,2,1].
回溯,代码:
vector<vector<int> >& permute(vector<int> vecInt) { vector<int> vecWorker; vector<vector<int> > vecPermu; helper(vecPermu, vecWorker, vecInt); return vecPermu; } void helper(vector<vector<int> >& vecPermu, vector<int>& vecWorker, const vector<int>& vecInt) { if (vecWorker.size() == vecInt.size()) { vecPermu.push_back(vecWorker); return; } for (int i = 0; i < vecInt.size(); i++) {
// 这里用visited记录更好一些,参见 Permutations II if (find(vecWorker.begin(), vecWorker.end(), vecInt[i]) != vecWorker.end()) continue; vecWorker.push_back(vecInt[i]); helper(vecPermu, vecWorker, vecInt); vecWorker.pop_back(vecInt[i]); } }