题目:

c++向量vector输出[_#include

 

 c++向量输出如下形式:["abc","acb","bac","bca","cab","cba"]

c++向量vector输出[_c++_02c++向量vector输出[_c++_03
#include <algorithm> // sort
#include "iostream"
#include "vector"
using namespace std;

class Solution {
public:
    vector<string> rec;
    vector<int> vis;

    void backtrack(const string& s, int i, int n, string& perm) {
        if (i == n) {
            rec.push_back(perm);
            return;
        }
        for (int j = 0; j < n; j++) {
            if (vis[j] || (j > 0 && !vis[j - 1] && s[j - 1] == s[j])) {
                continue;
            }
            vis[j] = true;
            perm.push_back(s[j]);
            backtrack(s, i + 1, n, perm);
            perm.pop_back();
            vis[j] = false;
        }
    }

    vector<string> permutation(string s) {
        int n = s.size();
        vis.resize(n);
        sort(s.begin(), s.end());
        string perm;
        backtrack(s, 0, n, perm);
        return rec;
    }
};

int main() {
    string s = "abc";
    int count = 0, i = 0;
    cout << "[";
    vector<string> res = Solution().permutation(s);
    count = res.size();
    // 使用迭代器 iterator 访问值
    vector<string>::iterator v = res.begin();
    while (v != res.end()) {
        if (i < count-1) {
            cout << *v << ", ";
        } else if (i == count-1) {
            cout << *v;
        }
        i++;
        v++;
    }
    cout << "]";
}
// https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/
View Code

题目网址:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/