Lesson 1 · Unit 03
Take it or leave it
Two branches per item, 2ⁿ subsets
What you practise
- Include/exclude for each item
- 2ⁿ subsets
Try a question from this lesson
Pick one
You pack for a trip and decide yes or no for each of 3 items. How many different bags can you end up with?
Correct answer
8
Why
Each decision doubles the possibilities: 2 × 2 × 2 = 8, counting the empty bag and the bag with everything. It is not 3 + 3, because the decisions combine with each other.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A tree of decisions
Take-or-leave is two branches per item, and a recursive call handles each branch. i is the item being decided and cur holds what was taken so far.
When every item has been decided, cur is one finished subset.
def subsets(s, i, cur):
if i == len(s):
print("{" + cur + "}")
return
subsets(s, i + 1, cur + s[i]) # take
subsets(s, i + 1, cur) # leave
subsets("ab", 0, "")function subsets(s, i, cur) {
if (i === s.length) {
console.log("{" + cur + "}");
return;
}
subsets(s, i + 1, cur + s[i]); // take
subsets(s, i + 1, cur); // leave
}
subsets("ab", 0, "");function subsets(
s: string, i: number, cur: string,
): void {
if (i === s.length) {
console.log("{" + cur + "}");
return;
}
subsets(s, i + 1, cur + s[i]); // take
subsets(s, i + 1, cur); // leave
}
subsets("ab", 0, "");Python noteStrings are immutable, so cur + s[i] builds a new string and the caller keeps its own cur unchanged.
TypeScript noteThe signature is wrapped over three lines. : void after the parameter list is the return type.
10 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
- 2× type the answer
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.