zoukankan      html  css  js  c++  java
  • 1384 全排列(回溯)

    1384 全排列

    基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
    收藏
    关注
    给出一个字符串S(可能有重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = "1312",
    输出为:
     
    1123
    1132
    1213
    1231
    1312
    1321
    2113
    2131
    2311
    3112
    3121
    3211
    Input
    输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)
    Output
    输出S所包含的字符组成的所有排列
    Input示例
    1312
    Output示例
    1123
    1132
    1213
    1231
    1312
    1321
    2113
    2131
    2311
    3112
    3121
    3211

    Dfs 遍历出所有结果,string 数组存出结果, sort对结果进行排序,unique 对结果去重(去重之前需要排序)

    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <cstring>
    
    using namespace std; 
    
    #define maxn 400000
    
    string result[maxn]; 
    char temp[maxn]; 
    char original[maxn]; 
    
    int numbers; 
    int len; 
    
    bool visit[maxn]; 
    
    void Dfs(int x) {
    
        if (x == len) {
            temp[x] = '';
            result[numbers++] = temp;
            return;
        }
    
        for (int i = 0; i < len; i++) {
            
            if (!visit[i]) {
                visit[i] = true; 
                temp[x] = original[i]; 
                Dfs(x + 1);
                visit[i] = false;
            }
        }
    }
    
    
    int main() {
    
        //cin >> original; 
        while (cin >> original) {
            len = strlen(original);
            numbers = 0; 
            memset(visit, false, sizeof(visit)); 
    
            Dfs(0);
        
            sort(result, result + numbers); 
            int m = unique(result, result + numbers) -  result; // string 方法去重
    
            for (int i = 0; i < m; i++) {
                cout << result[i] << endl; 
            }
        }
    
        return 0; 
    }
  • 相关阅读:
    webstorm配置github 以及本地代码上传github。
    日期控件------moment.js
    图片查看器
    日期
    配置一个node服务器
    git代码管理
    vue
    javascript (字符串, 数组, 对象 , 日期 和 操作元素节点 动画 定时器)
    html css
    JS常用方法
  • 原文地址:https://www.cnblogs.com/yi-ye-zhi-qiu/p/9411115.html
Copyright © 2011-2022 走看看