-
Notifications
You must be signed in to change notification settings - Fork 115
/
077-Combinations.cs
56 lines (45 loc) · 1.49 KB
/
077-Combinations.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//-----------------------------------------------------------------------------
// Runtime: 416ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _077_Combinations
{
public IList<IList<int>> Combine(int n, int k)
{
if (n <= 0 || k <= 0 || k > n) { return null; }
var results = new List<IList<int>>();
int i, j, count = 0;
var select = new bool[n];
for (i = 0; i < k; i++) { select[i] = true; }
bool hasNext;
while (true)
{
var result = new List<int>();
for (i = 0; i < n; i++)
if (select[i]) { result.Add(i + 1); }
results.Add(result);
hasNext = false;
count = 0;
for (i = 0; i < n - 1; i++)
{
if (select[i] && !select[i + 1])
{
select[i + 1] = true;
select[i] = false;
hasNext = true;
for (j = 0; j < i; j++)
select[j] = count-- > 0 ? true : false;
break;
}
if (select[i]) { count++; }
}
if (!hasNext) break;
}
return results;
}
}
}