LeetCode 46. Permutations(回溯法解决)

LeetCode 46. Permutations


题目描述: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]
]

题目理解:

输入一个每个元素都不重复的整形数组,输出该数组的全排列情况。

读题目后我就将目光放在了回溯法上面,借助一个标记数组,判断某位是否被标记,然后根据此进行结果的添加。思路早早确定,也是正确的,但是在tmp的处理上出现了问题,每次符合条件的都添加进去了但是在结果添加之后却没有将这次迭代中的元素删除,导致只添加了第一种符合条件的情况,发现这点后,将tmp重新更新,问题才得到解决。

class Solution {
public:
    vector<vector<int>> ans;
    vector<vector<int>> permute(vector<int>& nums) {
        int len = nums.size();
        vector<bool> flag(len,false);
        vector<int> tmp;
        allSort(nums,flag,tmp,len);
        return ans;
    }
    void allSort(vector<int>& nums,vector<bool>& flag,vector<int>& tmp,int len){
        if(tmp.size()==len){
            ans.push_back(tmp);
            return;
        }
        for(int i=0;i<len;i++){
            if(!flag[i]){
            tmp.push_back(nums[i]);
            flag[i] = true;
            allSort(nums,flag,tmp,len);
            flag[i] = false;
            if(!tmp.empty()) tmp.pop_back(); //Emphasize!!!!!Point!!!!!
            }
        }
    }
};

自己第一次独立写出回溯法类型题,精彩~~~

猜你喜欢

转载自blog.csdn.net/qq_40280096/article/details/81876433