https://leetcode.com/problems/bulb-switcher-ii/description/
int flipLights(int n, int m) {
if (m == 0 || n == 0) return 1;
if (n == 1) return 2;
if (n == 2) return m == 1? 3:4;
if (m == 1) return 4;
return m == 2? 7:8;
}
or,
void dfs(int flips, int m, vector<unordered_set<int>>& status) {
if(m==0) {
status[0].insert(flips);
return;
}
int f;
f = flips^1;
if(!status[m-1].count(f)) { status[m-1].insert(f); dfs(f, m-1, status); }
f = flips^2;
if(!status[m-1].count(f)) { status[m-1].insert(f); dfs(f, m-1, status); }
f = flips^4;
if(!status[m-1].count(f)) { status[m-1].insert(f); dfs(f, m-1, status); }
f = flips^8;
if(!status[m-1].count(f)) { status[m-1].insert(f); dfs(f, m-1, status); }
}
int flipLights(int n, int m) {
if(m==0) return 1;
vector<unordered_set<int>> status(m);
dfs(15, m, status);
unordered_set<vector<bool>> st;
for(int s: status[0]) {
vector<bool> lit(n, true);
int x;
x = s & 1;
if(x) for(int i=0; i<n; i++) lit[i] = (!lit[i]);
x = (s>>1) & 1;
if(x) for(int i=1; i<n; i+=2) lit[i] = (!lit[i]);
x = (s>>2) & 1;
if(x) for(int i=0; i<n; i+=2) lit[i] = (!lit[i]);
x = (s>>3) & 1;
if(x) for(int i=0; i<n; i+=3) lit[i] = (!lit[i]);
st.insert(lit);
}
return st.size();
}
No comments:
Post a Comment