思路:
排列不重复,在实际使用中体现在在某一层排列中出现3个2,我们其实需要这个2出现一次,也就是说在同一层的排列中,我们只要1次2进入下层,其他的不用参与分支。怎么处理?可以对原排列按顺序排起来,让2相邻,第一次2进去后,然后撤回嘛,如果发现上一次元素和这次相同,那就可以continue了!不,还要保证上一个元素没被vis,因为撤回了,没被vis,为什么要加这个呢,因为如果vis了,有可能是不同层的,上一层使用2,下一层我当然可以继续使用2呀~~在这里全排列不重复和位置有关,而不是值了,所以vis从正常的set变成了vector bool型
class Solution {
public:
vector<string>res;
vector<int> vis;
vector<string> permutation(string s) {
//试下暴力回溯
string temp;
vis.resize(s.size()); //为了提前分配空间,只能使用全局变量, 然后在主函数中resize!!!不然vis[i]会报错
sort(s.begin(),s.end());
dfs(s,temp,0);
return res;
}
void dfs(const string &s,string & temp,int index){
if(index==s.size()){
res.push_back(temp); //这一层temp还没进呢,何来的pop没事~
return;
}
for(int i=0;i<s.size();i++){
if (vis[i] || (i > 0 && !vis[i - 1] && s[i - 1] == s[i])){
continue;
}
vis[i]=true;
temp.push_back(s[i]);
dfs(s,temp,index+1);
temp.pop_back();
vis[i]=false;
}
}
};
字符串的相加
代码:
按照竖排加法的规则,两个数字都从末位开始相加,加的变成数字,然后转换成字符进入string里面,她这边数字转字符不用to_string而是+‘0’,字符转数字-‘0’. 最后反转。
class Solution {
public:
string addStrings(string num1, string num2) {
string s; //注意到在数字后面+'0'能变成string,在string上面-'0'能变成数字
int i=num1.size()-1; int j=num2.size()-1; int add=0;
while(i>=0 || j>=0 || add!=0){
int x= i>=0 ? num1[i]-'0':0;
int y= j>=0 ? num2[j]-'0':0;
int res=x+y+add;
s.push_back(res%10+'0');
add=res/10;
i--;
j--;
}
reverse(s.begin(),s.end());
return s;
}
};
字符串相乘
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") {
return "0";
}
string ans = "0";
int m = num1.size(), n = num2.size();
for (int i = n - 1; i >= 0; i--) {
string curr; //注意到curr虽然是字符串形式,可以往里面直接存数字进去,只是这个数字是ASCII形式,我要通过对他遍历元素去字符!
int add = 0;
for (int j = n - 1; j > i; j--) {
curr.push_back(0+'0');
}
int y = num2.at(i) - '0';
for (int j = m - 1; j >= 0; j--) {
int x = num1.at(j) - '0';
int product = x * y + add;
curr.push_back(product % 10+'0');
add = product / 10;
}
if (add != 0) {
curr.push_back(add % 10+'0');
add /= 10;
}
reverse(curr.begin(), curr.end());
ans = addStrings(ans, curr);
}
return ans;
}
string addStrings(string &num1, string &num2) {
int i = num1.size() - 1, j = num2.size() - 1, add = 0;
string ans;
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.at(i) - '0' : 0;
int y = j >= 0 ? num2.at(j) - '0' : 0;
int result = x + y + add;
ans.push_back(result % 10+'0');
add = result / 10;
i--;
j--;
}
reverse(ans.begin(), ans.end());
return ans;
}
};