剑指offer 最小的K个数

来源:互联网 发布:阿里云如何备份 编辑:程序博客网 时间:2024/06/05 14:42

最小的K个数

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。

我的解答

思路

这道题目我是参考一个博客的,具体地址找不到了,这里我就说说现在我对这道题目的理解吧,这道题目核心就是递归,可能我们写过很多树的递归,遇到这种递归是束手无策,这道题目就是在当前序列中每一个字符都需要放到当前头部的位置(除了和头部相同的字符),也就是下面代码中index的位置,然后递归到下一层,直到交换到尾部,存放入res中。相当于是每个字符轮流坐庄,至于下面的你们自己排队,排到最后就剩下两个了,互换一下就可以了,这个过程读者可以模拟一下,整个程序就完结了。

代码

////  main.cpp//  offer27////  Created by 李林 on 16/7/26.//  Copyright © 2016年 李林. All rights reserved.//#include <iostream>#include <cstdio>#include <vector>#include <string>#include <algorithm>using namespace std;class Solution {public:    //交换地址。    void swap(char* c1, char* c2){        char temp = *c1;        *c1 = *c2;        *c2 = temp;    }    void MyPermutation(int index, string str, vector<string> &res){        int len = str.length();        if(index==len-1){            res.push_back(str);        }        else{            for(int i=index; i<len; i++){                //本身也需要交换+不可重复交换。                if(i==index || str[index]!=str[i]){                    swap(&str[index], &str[i]);                    MyPermutation(index+1, str, res);                    swap(&str[index], &str[i]);                }            }        }    }    vector<string> Permutation(string str) {        vector<string> res;        if(str.length()>0){            MyPermutation(0, str, res);            sort(res.begin(), res.end());        }        return res;    }    void Show(vector<string> res){        int size = res.size();        for(int i=0; i<size; i++){            cout<<res[i]<<endl;        }    }};int main() {    Solution s;    vector<string> result = s.Permutation("ccba");    s.Show(result);    return 0;}
0 0
原创粉丝点击