题解 | 游游的字符重排

游游的字符重排

https://www.nowcoder.com/practice/39694c1e34444bc18ffd9ed53312b50e

DFS枚举并回溯

#include <iostream>
#include<string>
#include<vector>
using namespace std;

int cnt=0;
vector<int>freq;
int n;
void back(int pos,char prev){
    if(pos==n){
        cnt++;
        return ;
    }
    for(char c='a';c<='z';c++){
        int idx=c-'a';
        if(freq[idx]>0&&c!=prev){
            freq[idx]--;
            back(pos+1,c);
            freq[idx]++;
        }
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string s;
    cin>>s;
    n=s.size();
    freq.resize(26,0);
    for(char c:s){
        freq[c-'a']++;
    }
    back(0,-1);
    cout<<cnt<<endl;
    return 0;
}

全部评论

相关推荐

12-01 14:24
吉首大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务