I'm struggling to figure out the formula for this problem:
Given an array of n
numbers and a limit k
, count all non-duplicate combinations that has at least size k
.
E.g.: A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3]
- The array can contain duplicate numbers.
E.g.: A=[1,1,2] k = 2 output = 3 // [1,1],[1,2],[1,1,2]
but [1,2],[2,1], etc.
are not accepted.
I was able to solve it using backtracking
but TLE. I've been trying to find a formula from problems like find all combinations of n
or find all combinations of size k
without success.
I've figured out this table so far:
row = k
col = n
1 2 3 4 5
---------
1| 1 2 3 4 5
2| 1 3 6 10
3| 1 4 10
4| 1 5
And the formula (not quite what I want) is:
combinations of size i with j numbers:
dp[i][j] = dp[i][j-1] + dp[i-1][j-1]
count(n,k) combinations of size k with n numbers
count(2,1) = 2
count(4,3) = count(3,3) + count(3,2) = 1 + 3 = 4
count(5,2) = count(4,2) + count(4,1) = 6 + 4 = 10
and so on
Update
Based on Oliver Dain's answer, here's the code if you're interested
def count_combinations(n, k):
count = 0
for i in range(k, n + 1):
count += math.factorial(n)/(math.factorial(i)*math.factorial(n - i))
return int(count)