diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /combinations.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'combinations.cpp')
-rw-r--r-- | combinations.cpp | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/combinations.cpp b/combinations.cpp new file mode 100644 index 0000000..f524fc2 --- /dev/null +++ b/combinations.cpp @@ -0,0 +1,39 @@ +// 77. Combinations +#include "leetcode.h" + +/* + * given two integers 'n' and 'k', return all possible combinations of 'k' + * numbers chosen from the range '[1, n]'. you may return the answer in any + * order + */ + +class Solution { +public: + vvd(int) combine(int n, int k) { + vvd(int) ans; + int i = 0; + vector<int> p(k, 0); + while (i >= 0) { + p[i]++; + if (p[i] > n) + --i; + else if (i == k - 1) + ans.push_back(p); + else + i++, p[i] = p[i - 1]; + } + return ans; + } +}; + +int main() { + Solution obj; + for (auto i : obj.combine(4, 2)) + for (auto j : i) + printf("%d ", j); // expect: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] + printf("\n"); + for (auto i : obj.combine(1, 1)) + for (auto j : i) + printf("%d ", j); // expect: [[1]] + printf("\n"); +} |