题目:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼出得搜数字中最小的一个。例如输入{3,32,321},则打印出这3个数字能排成的最小数字321323.
方法一:
分析:先求出这个数组中所有数字的全排列,然后把每个排列拼接起来,最后求出拼接起来的数字的最小值。
源代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
void Permutation(int *arr, int length, int index, vector<int> &vec);
void swap(int *A, int *B)
{
int temp = *A;
*A = *B;
*B = temp;
}
void Permutation(int *arr, int length)
{
if (arr == nullptr || length <=0)
return;
vector<int> vec;
Permutation(arr, length, 0, vec);//数组的全排列
int minNum = *vec.cbegin();
for (auto it = vec.cbegin(); it != vec.cend(); ++it)
{
cout << *it << " ";
if (minNum > *it)
minNum = *it;
}
cout << "\nMin = " << minNum << endl;
}
void Permutation(int *arr, int length, int index, vector<int> &vec)
{
if (index == length)
{
string str;
for (int i = 0; i < length; ++i)
{
str += to_string(arr[i]);
}
int temp = stoi(str);
vec.push_back(temp);
}
else
{
for (int i = index; i < length; ++i)
{
swap(arr + i, arr + index);
Permutation(arr, length, index + 1, vec);
swap(arr + i, arr + index);
}
}
}
void test1()
{
cout << "=================test1:{3,32,321}=========" << endl;
int arr[] = { 3, 32, 321 };
Permutation(arr, 3);
cout << endl;
}
int main()
{
test1();
system("pause");
return 0;
}
运行结果:
=================test1:{3,32,321}=========
332321 332132 323321 323213 321323 321332
Min = 321323
请按任意键继续. . .
方法二:
待续。。。。