33. 把数组排成最小的数(C++版本)

实现要点:
将数组按照特定规则排序,依次组合起来就是最小的数。
排序规则为 A + B < B + A时为true。

代码实现:

std::string GetMinNumber(const std::vector<int>& datas)
{
	if (datas.empty()) return "";

	std::vector<std::string> tempDatas;
	for (auto& curData : datas) tempDatas.push_back(std::to_string(curData));

	auto sortFunc = [](const std::string& left, const std::string& right) {return left + right < right + left; };
	std::stable_sort(tempDatas.begin(), tempDatas.end(), sortFunc);

	std::string minNum;
	for (auto& curData : tempDatas) minNum += curData;
	
	return minNum;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最小组合问题是一个经典的编程题目,主要涉及到数组和排序算法的应用。给定一个正整数组,你需要找出所有可能由这些字组成的不同整,并返回其中的最小值。在C++中,你可以采用递归或者动态规划的方法来解决这个问题。 以下是使用递归的一个简单思路: 1. 定义一个递归函,该函接受一个数组和当前组合的起始和结束索引。 2. 遍历数组,对于每个起始位置,尝试添加当前位置的字到当前组合,并递归调用函处理下一个位置。 3. 在递归过程中,记录并更新最小组合。 4. 当遍历完数组时,返回找到的最小组合。 下面是基本的递归代码示例: ```cpp #include <iostream> #include <vector> #include <string> using namespace std; string combine(vector<int>& nums, int start, int end, string prefix = "") { if (start > end) { // 如果到达了数组末尾,返回当前组合 return prefix; } // 尝试将当前字加到前缀 string result1 = combine(nums, start + 1, end, to_string(nums[start]) + prefix); // 不加当前字,直接递归处理下一个 string result2 = combine(nums, start + 1, end, prefix); // 返回两者中的较小者 return min(result1, result2); } int smallestCombination(vector<int>& nums) { sort(nums.begin(), nums.end()); // 先对数组进行排序 return combine(nums, 0, nums.size() - 1); // 从头开始递归 } int main() { vector<int> nums = {1, 2, 3}; int result = smallestCombination(nums); cout << "The smallest combination is: " << result << endl; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值