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;
    }
    

  • 相关阅读:
    PAT (Basic Level) Practise 1013 数素数
    PAT (Basic Level) Practise 1014 福尔摩斯的约会
    codeforces 814B.An express train to reveries 解题报告
    KMP算法
    rsync工具
    codeforces 777C.Alyona and Spreadsheet 解题报告
    codeforces 798C.Mike and gcd problem 解题报告
    nginx + tomcat多实例
    MongoDB副本集
    指针的艺术(转载)
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787065.html
Copyright © 2011-2022 走看看