剑指offer-把数组排成最小的数

来源:互联网 发布:java语言程序设计自学 编辑:程序博客网 时间:2024/05/21 22:33

题目:给一个正整数数组,例如{1,2,3,4},将里面的数字组合,求最小的数,应为1234

全排列

我的思路是,如果我们将能够组合的所有形式列举出来,这就转化成了一个求最小值的问题。所以问题的根本写出全排列。(应该也可以通过比较第一位应该选哪一个,但是要考虑的情况有点多,我就暴力的求了)

class Solution {public:string PrintMinNumber(vector<int> numbers) {    //思路:首先将vector<int> 转化成vector<string>    int numLen = numbers.size();    stringstream ss;    string reStr;    if (numLen == 1) {        ss << numbers[0];        ss >> reStr;        return reStr;    }    if(numLen==0)        return "";    //将所有int转化为string    vector<string> strVec;    for (int i = 0; i < numLen; i++) {        stringstream sss;        string temp;        sss << numbers[i];        sss >> temp;        strVec.push_back(temp);    }    string maxStr;    long long int maxNum;    maxStr = conj(strVec);    ss << maxStr;    ss >> maxNum;    maxNum = findMax(strVec, maxNum, 0);    stringstream news;    news << maxNum;    string re;    news >> re;    return re;}long long int findMax(vector<string> strVec, long long int& tempMax, int begin) {    int numLen = strVec.size();    long long int maxNum;    stringstream ss;    if (begin == numLen - 1) {        string temp = conj(strVec);        ss << temp;        ss >> maxNum;        if (maxNum<tempMax)            tempMax = maxNum;        return tempMax;    }    for (int i = begin; i<numLen; i++) {        swap(strVec, begin, i);        maxNum = findMax(strVec, tempMax, begin + 1);        if (maxNum<tempMax)            tempMax = maxNum;        swap(strVec, begin, i);    }    return tempMax;}void swap(vector<string>& strVec, int i, int j) {    string temp = strVec[i];    strVec[i] = strVec[j];    strVec[j] = temp;}string conj(vector<string>& strVec) {    string re;    int len = strVec.size();    for (int i = 0; i<len; i++) {        re += strVec[i];    }    return re;}};

其中全排列用的是递归实现的,大家有简单的方法,欢迎交流。

原创粉丝点击