zoukankan      html  css  js  c++  java
  • [CareerCup] 9.5 Permutations 全排列

    9.5 Write a method to compute all permutations of a string.

    LeetCode上的原题,请参加我之前的博客Permutations 全排列Permutations II 全排列之二

    解法一:

    class Solution {
    public:
        vector<string> getPerms(string &s) {
            vector<string> res;
            getPermsDFS(s, 0, res);
            return res;
        }
        void getPermsDFS(string &s, int level, vector<string> &res) {
            if (level == s.size()) res.push_back(s);
            else {
                for (int i = level; i < s.size(); ++i) {
                    swap(s[level], s[i]);
                    getPermsDFS(s, level + 1 ,res);
                    swap(s[level], s[i]);
                }
            }
        }
    };

    解法二:

    class Solution {
    public:
        vector<string> getPerms(string s) {
            vector<string> res;
            vector<bool> visited(s.size(), false);
            getPermsDFS(s, 0, visited, "", res);
            return res;
        }
        void getPermsDFS(string s, int level, vector<bool> &visited, string out, vector<string> &res) {
            if (level == s.size()) res.push_back(out);
            else {
                for (int i = 0; i < s.size(); ++i) {
                    if (!visited[i]) {
                        visited[i] = true;
                        out.push_back(s[i]);
                        getPermsDFS(s, level + 1, visited, out , res);
                        out.pop_back();
                        visited[i] = false;
                    }   
                }
            }
        }
    };

    解法三:

    class Solution {
    public:
        vector<string> getPerms(string s) {
            if (s.empty()) return vector<string>(1, "");
            vector<string> res;
            char first = s[0];
            string remainder = s.substr(1);
            vector<string> words = getPerms(remainder);
            for (auto &a : words) {
                for (int i = 0; i <= a.size(); ++i) {
                    string out = insertCharAt(a, first, i);
                    res.push_back(out);
                }
            }
            return res;
        }   
        string insertCharAt(string s, char c, int i) {
            string start = s.substr(0, i);
            string end = s.substr(i);
            return start + c + end;
        }
    };
  • 相关阅读:
    移动比联通强的帖子的再次探讨
    清除或选中所有的checkbox
    textbox获得焦点显示JS日历控件
    Repeater分页
    互联网协会:博客推行实名制已成定局
    新闻内容分页
    获得显示器设置的分辨率
    node.js应用生成windows server的plugin——winser
    CSS基础
    git使用
  • 原文地址:https://www.cnblogs.com/grandyang/p/4822859.html
Copyright © 2011-2022 走看看