wisdompeak / LeetCode

This repository contains the solutions and explanations to the algorithm problems on LeetCode. Only medium or above are included. All are written in C++/Python and implemented by myself. The problems attempted multiple times are labelled with hyperlinks.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question about the for loop condition to efficientlly iterate all subset

qh-huang opened this issue · comments

commented

Hi wisdompeak,

In the README.md, you mentioned a template

  for (int state=1; state<(1<<n); state++)  
      for (int subset=state; subset>0; subset=(subset-1)&state)
      {
          dp[state] = DoSomething(dp[subset]);
      }  

The inner for loop condition implies when (subset-1&state) == 0, there's no need to search the next subset with the same state.

However, I'm confuse about the reason, would you please explain it or give me some hint?
Thanks.

if you write something like for (int subset=state; subset>=0; subset=(subset-1)&state), the loop would never end.