Permutations

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], and [3,2,1].

class Solution {
public:
    vector<vector<int> > ans;
    void dfs(vector<int> &num,vector<int> &path){
        if (path.size() == num.size()){
            ans.push_back(path);
            return;
        }
        for(int j = 0; j < num.size(); j++){
            int ok = 1;
            for(int i = 0; i < path.size(); i++){
                if (path[i] == num[j]){
                    ok = 0;
                    break;
                }
            }
            if (!ok){
                continue;
            }
            path.push_back(num[j]);
            dfs(num,path);
            path.resize(path.size() -1);
        }

    }
    vector<vector<int> > permute(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ans.clear();
        vector<int> path;
        sort(num.begin(),num.end());
        dfs(num,path);
        return ans;
    }
};

原文链接: https://www.cnblogs.com/kwill/p/3185473.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/95547

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午3:09
下一篇 2023年2月10日 上午3:09

相关推荐