zoukankan      html  css  js  c++  java
  • [算法] 带有条件的全排列 [dfs + set]

    由于排列的问题能够很好的考查对递归的掌握程度,并且实现也非常的简单,因此经常会出现在面试之中。
    下面就是某著名互联网公司的一道关于排列的面试题:
    题目:输入一个字符串S和一个整数N,其中S中的各个字符均不相等,并且N小于等于S的长度,请输出由S中字符组成的长度为N的所有的排列。
    如:字符串是"abc", N=2, 则输出:ab, ac, bc, ba, ca, cb
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <cstdlib>
    #include <cstdio>
    #include <cmath>
    #include <vector>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <bitset>
    #include <list>
    #include <map>
    #include <set>
    #include <iterator>
    #include <algorithm>
    #include <functional>
    #include <utility>
    #include <sstream>
    #include <climits>
    #include <cassert>
    #define BUG puts("here!!!");
    
    using namespace std;
    const int N = 1005;
    int cnt = 2;
    void swap(char &a, char &b) {
    	char temp = a;
    	a = b;
    	b = temp;
    }
    set<string> S;
    void dfs(char *str, char *begin) {
    	if(*begin == '\0') {
    		S.insert(str+3);
    		return;
    	}
    	for(char *p = begin; *p != '\0'; p++) {
    		swap(*p, *begin);
    		dfs(str, begin+1);
    		swap(*p, *begin);
    	}
    }	
    void show() {
    	set<string>::iterator it;
    	for(it = S.begin(); it != S.end(); ++it) {
    		cout << *it << endl;
    	}
    }
    int main() {
    	char s[10] = "abcde";
    	dfs(s, s);
    	show();
    	return 0;
    }
    

  • 相关阅读:
    mybatis学习笔记
    markdownPad常用功能示例
    2018-2019-2 《Java程序设计》第3周学习总结
    2018-2019-2 《Java程序设计》第2周学习总结
    2018-2019-2 《Java程序设计》第1周学习总结
    Djnago models 一对多、多对多
    Superset 安装
    lvm 添加分区
    partprobe 重新检测Linux系统分区
    Docker 、Docker Compose 安装
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787065.html
Copyright © 2011-2022 走看看