zoukankan      html  css  js  c++  java
  • 46. Permutations(medium, backtrack, 重要)

    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;
    	}
    }
    
  • 相关阅读:
    [Codeup 25482]选美
    [Codeup 25481] swan
    暑假集训D12总结
    [技术]浅谈重载操作符
    2020年寒假第6次学*进度记录
    2020年寒假第5次学*进度记录
    2020年寒假第4次学*进度记录
    “家庭记账本”软件开发(1)
    阅读《梦断代码》随笔(1)
    2020年寒假第三次学*进度记录
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7505537.html
Copyright © 2011-2022 走看看