Leetcode每日一题字符串的排列
原题链接
开始的时候,我直接当整数的排列来写
没有去重wa了一发
class Solution {
public:
vector<string> res;
void dfs(string s, string cur, int u, int state)
{
if(u == s.size())
{
res.push_back(cur);
return ;
}
for (int i = 0; i < s.size(); i ++ )
{
if(state >> i & 1) continue;
dfs(s, cur + s[i], u + 1, state | 1 << i);
}
}
vector<string> permutation(string s) {
dfs(s, "", 0, 0);
return res;
}
};
考虑集合存一下答案可以过,发现时间复杂度有点低
一开始用的是枚举,其实可以交换减少空间存储,并且达到剪枝的目的,就是在每一层搜索的时候用集合存当前层的已经遍历过的字母
方法一:枚举
四个参数(源字符串,当前字符串,枚举到第几个字母,当前字母是否使用过)
class Solution {
public:
vector<string> res;
unordered_set<string> S;
void dfs(string s, string cur, int u, int state)
{
if(u == s.size())
{
if(!S.count(cur))
{
S.insert(cur);
res.push_back(cur);
}
return ;
}
for (int i = 0; i < s.size(); i ++ )
{
if(state >> i & 1) continue;
dfs(s, cur + s[i], u + 1, state | 1 << i);
}
}
vector<string> permutation(string s) {
dfs(s, "", 0, 0);
return res;
}
};
方法二:交换字母(记得还原)
class Solution {
public:
vector<string> res;
void dfs(string &s, int u)
{
if(u == s.size() - 1)
{
res.push_back(s);
return ;
}
set<char> S;
for (int i = u; i < s.size(); i ++ )
{
if(S.count(s[i])) continue;
S.insert(s[i]);
swap(s[i], s[u]);
dfs(s, u + 1);
swap(s[i], s[u]);
}
}
vector<string> permutation(string s) {
dfs(s, 0);
return res;
}
};
Acwing每日一题方格涂色(枚举)
原题链接
只有四个角的格子会影响答案,枚举16种情况,只要找到一个四条边都不矛盾的方案就成立
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
int u, r, d, l;
bool check(int state)
{
int a = state >> 0 & 1, b = state >> 1 & 1;
int x = state >> 2 & 1, y = state >> 3 & 1;
if(!(a + b <= u && u <= a + b + n - 2)) return false;
if(!(b + y <= r && r <= b + y + n - 2)) return false;
if(!(x + y <= d && d <= x + y + n - 2)) return false;
if(!(a + x <= l && l <= a + x + n - 2)) return false;
return true;
}
int main()
{
int T;
scanf("%d", &T);
while (T -- )
{
scanf("%d %d %d %d %d", &n, &u, &r, &d, &l);
bool flag = false;
for (int i = 0; i < 16; i ++ )
if(check(i))
{
flag = true;
break;
}
if(flag) puts("YES");
else puts("NO");
}
return 0;
}