Leetcode 46. Permutations 全排列 标准回溯法

class Solution {
public:
	void fun(vector<vector<int>> &ans, vector<int>& nums, vector<int> &temp,int index)
	{
		if (index == nums.size()-1) 
		{
			temp.push_back(nums[index]);
			ans.push_back(temp);
			temp.pop_back();
			return;
		}
		else 
		{
			for (int i = index; i < nums.size(); i++) 
			{
				temp.push_back(nums[i]);
				swap(nums[i],nums[index]);
				fun(ans, nums, temp, index+1);
				temp.pop_back();
				swap(nums[i], nums[index]);
			}
		}
	}
	vector<vector<int>> permute(vector<int>& nums)
	{
		vector<vector<int>> ans;
		vector<int> temp;
		fun(ans, nums,temp, 0);
		return ans;

	}
};

void backtrack (int t) {
       if (t>n) output(x);
       else {
         for (int i=f(n,t); i<=g(n,t); i++) {
               x[t]=h(i);
              if (constraint(t)&&bound(t)) backtrack(t+1);
        }
     }
}

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭