46. Permutations&&面试题 08.07. Permutation I LCCI

Problem

46

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

面试题 08.07

Write a method to compute all permutations of a string of unique characters.

Example1

Input: S = “qwe”
Output: [“qwe”, “qew”, “wqe”, “weq”, “ewq”, “eqw”]

Example2

Input: S = “ab”
Output: [“ab”, “ba”]

Solution

解决一个回溯问题,实际上就是一个决策树的遍历过程。

你只需要思考 3 个问题:

1、路径:也就是已经做出的选择。

2、选择列表:也就是你当前可以做的选择。

3、结束条件:也就是到达决策树底层,无法再做选择的条件。

代码方面,回溯算法的框架:

result = []
def backtrack(路径, 选择列表):
    if 满足结束条件:
        result.add(路径)
        return

    for 选择 in 选择列表:
        做选择
        backtrack(路径, 选择列表)
        撤销选择

其核心就是 for 循环里面的递归,在递归调用之前「做选择」,在递归调用之后「撤销选择」,特别简单。

画出整个搜索树

在这里插入图片描述

Solution for 46

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> ret;
        if(nums.empty())
            return ret;
        vector<bool> used(nums.size(),false);
        vector<int> tmp;

        backtrack(nums,used,tmp,ret);

        return ret;
        
    }

    void backtrack(vector<int>& nums,vector<bool> &used,vector<int> &tmp,vector<vector<int>> &ret)
    {
        if(tmp.size() == nums.size())
        {
            ret.push_back(tmp);
            return;
        }

        for(int i = 0;i<nums.size();++i)
        {
            if(used[i] == true)
                continue;
            else
            {
                used[i] = true;
                tmp.push_back(nums[i]);

                backtrack(nums,used,tmp,ret);

                tmp.pop_back();
                used[i] = false;
            }
        }
    }
};

Solution for 面试题08.07

class Solution {
public:
    vector<string> permutation(string S) {
        vector<string> ret;
        if(S.empty())
            return ret;
        string tmpS = "";
        backtrack(S,tmpS,ret);

        return ret;

    }

    void backtrack(string &S,string &tmpS,vector<string> &ret)
    {
        if(tmpS.length() == S.length())
        {
            ret.push_back(tmpS);
        }

        for(int i = 0;i<S.length();++i)
        {
            if(tmpS.find(S[i]) != string::npos)
                continue;
            tmpS += S[i];
            backtrack(S,tmpS,ret);
            tmpS = tmpS.substr(0,tmpS.length() - 1);
        }
    }
};

Ref

https://mp.weixin.qq.com/s/nMUHqvwzG2LmWA9jMIHwQQ

发布了547 篇原创文章 · 获赞 217 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105181775
今日推荐