拼接数组中的数字( 有问题??? )
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
当仿函数中使用<=进行比较时, 如果有过多的0, 会造成溢出, 为什么?????
class Solution {
public:
class Itos
{
public:
string operator()(int val)
{
return to_string(val);
}
};
class Cmp
{
public:
bool operator()(string& s1, string& s2)
{
// 如果是<= 当有过多的0时, 会造成溢出
if(s1 + s2 < s2 + s1)
return true;
else
return false;
}
};
string minNumber(vector<int>& nums) {
vector<string> v;
v.resize(nums.size());
transform(nums.begin(), nums.end(), v.begin(), Itos());
sort(v.begin(), v.end(), Cmp());
string res = "";
for(auto& s : v)
{
res = res + s;
}
return res;
}
};
字符串全排列
- 原来的思路是对每一个位, 都遍历所有字符, 但是会存在重复位需要用visited标记, 同时相同排列需要最后使用set去重.
- 新思路 : 使用swap避免了visited标记, 将所需字母交换到当前位后, 每次只遍历当前需要确定的位到最后一位, 巧妙的进行了剪枝; 同时在每一位循环中, 使用一个set, 避免当前位出现重复字母的情况; 而且全程在原字符串s上操作, 避免了新建一个字符串记录.
class Solution {
public:
vector<string> res;
/*
vector<bool> visited;
void dfs(string& s, string& temp)
{
if(temp.size() == s.size())
{
res.push_back(temp);
return ;
}
for(int i = 0; i < s.size(); i++)
{
if(visited[i] == false)
{
temp += s[i];
visited[i] = true;
dfs(s, temp);
visited[i] = false;
temp = temp.substr(0, temp.size()-1);
}
}
}
*/
void swap(int i, int j, string& s)
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
void dfs(int x, int n, string& s)
{
if(x == n-1)
{
res.push_back(s);
return ;
}
set<char> st;
for(int i = x; i < n; i++)
{
if(st.find(s[i]) != st.end()) continue;
st.insert(s[i]);
swap(i, x, s