1. Bitmask Exhaustive Enumeration (1 to 2^9 - 1)
Intuition
Each subset of {1..9} can be represented by a 9-bit integer mask from 1 to (1<<9)-1. For each mask, count set bits. If set bits == k, compute sum of corresponding numbers. If sum == n, add subset to result.
When to apply: Feasible because domain size is fixed at 9 digits.
Algorithm
- Loop
maskfrom 1 to(1 << 9) - 1: - - If
__builtin_popcount(mask) != k, continue. - - Sum values corresponding to set bits.
- - If sum == n, collect combination into
result. - Return
result.
#include <iostream>#include <vector> using namespace std; class Solution {public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> result; for (int mask = 1; mask < (1 << 9); mask++) { if (__builtin_popcount(mask) == k) { int sum = 0; vector<int> current; for (int i = 0; i < 9; i++) { if (mask & (1 << i)) { int val = i + 1; sum += val; current.push_back(val); } } if (sum == n) { result.push_back(current); } } } return result; }}; int main() { Solution sol; auto res = sol.combinationSum3(3, 7); for (const auto& c : res) { cout << "[ "; for (int v : c) cout << v << " "; cout << "] "; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^9 * 9) = O(1)— Evaluates exactly 512 bitmasks with 9 bit tests each. - Space complexity:
O(1)— Uses constant memory beyond the output list.