question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
prime-number-of-set-bits-in-binary-representation
Brian Kernighan's Algorithm | Easiest | Simplest | No Where On Youtube
brian-kernighans-algorithm-easiest-simpl-tr36
IntuitionWe need to iterate to each number, calculate the number of set bits and check whether they are prime or not.ApproachWe first iterate to each number usi
rohanmalhotracodes
NORMAL
2025-01-30T20:43:15.408978+00:00
2025-01-30T20:43:15.408978+00:00
128
false
# Intuition We need to iterate to each number, calculate the number of set bits and check whether they are prime or not. # Approach We first iterate to each number using the loop while(left<=right){ left++ } to iterate to each value in the range [left,right] Then, we count the number of primes in each value we iterate to using Brian Kernighan's Algorithm which states while(digit){ digit&=(digit-1); //This flips each set bit starting from right to left count++; } then we compare the count which we get above with 2,3,5,7,11,13,17,19 directly instead of writing a code to check prime because left<=right<=10^6 which means log2(10^6+1)=19.9 which is 20 that is , our number can have maximum 20 set bits so we need all the prime number less than equal to 20. finally we return the count after checking if each value is prime or not. # Complexity - Time complexity: - R-L=N O(N) - Space complexity: O(1), number of additional variables is fixed # Code ```cpp [] class Solution { int BrianKernighan(int digit){ int set_bits=0; while(digit){ set_bits+=(digit&1); digit=digit>>1; } return set_bits; } bool check_prime(int digit){ if(digit==1){ return 0; } for(int i=2;i<=sqrt(digit);i++){ if((digit%i)==0){ return 0; } } return 1; } public: int countPrimeSetBits(int left, int right) { int primes=0; while(left<=right){ int set_bits=BrianKernighan(left); primes+=check_prime(set_bits); left++; } return primes; } }; ```
1
0
['Math', 'Bit Manipulation', 'C++']
0
prime-number-of-set-bits-in-binary-representation
☑️ Finding Prime Number of Set Bits in Binary Representation. ☑️
finding-prime-number-of-set-bits-in-bina-ic8v
Code
Abdusalom_16
NORMAL
2025-01-26T17:29:50.741711+00:00
2025-01-26T17:29:50.741711+00:00
36
false
# Code ```dart [] class Solution { int countPrimeSetBits(int left, int right) { int result = 0; for(int i = left; i <= right; i++){ String conv = i.toRadixString(2); int count = 0; for(int j = 0; j < conv.length; j++){ if(conv[j] == "1"){ count++; } } int countDividers = 0; for(int j = 1; j <= count; j++){ if(count % j == 0){ countDividers++; } } if(countDividers == 2){ result++; } } return result; } } ```
1
0
['Math', 'Bit Manipulation', 'Dart']
0
prime-number-of-set-bits-in-binary-representation
Bit Manipulation | Easy | Beats 100% | ✅
bit-manipulation-easy-beats-100-by-batma-sw05
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires counting numbers within a given range [left, right] where the numb
batman505
NORMAL
2024-10-01T08:52:25.078647+00:00
2024-10-01T08:52:25.078711+00:00
75
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires counting numbers within a given range `[left, right]` where the number of set bits (1s in the binary representation) of each number is prime. The solution involves checking each number, counting its set bits, and then determining if that count is a prime number.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Prime Checking: A helper function isPrime(int n) is used to determine if a number n is prime. It checks for divisibility starting from 2 up to n-1.\n\n2. Counting Set Bits: For each number in the range [left, right], the number of set bits is counted using Brian Kernighan\'s algorithm:\n\n * num = num & (num - 1) reduces the number of set bits in each step, effectively counting the set bits until the number becomes 0.\n3. Prime Set Bits: After counting the set bits for a number, the isPrime function checks if the count is prime. If so, the answer counter ans is incremented.\n\n4. Final Answer: The process is repeated for all numbers in the given range, and the final count of numbers with a prime number of set bits is returned.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\nprivate:\n bool isPrime(int n) {\n if(n<=1) return false;\n for(int i=2; i<n; i++) {\n if(n%i==0) return false;\n }\n return true;\n }\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans = 0;\n for(int i=left; i<=right; i++) {\n int count = 0;\n int num = i;\n while(num!=0) {\n num = num&(num-1);\n count++;\n }\n if(isPrime(count)) ans++;\n }\n return ans;\n }\n};\n```
1
0
['Bit Manipulation', 'C++']
0
prime-number-of-set-bits-in-binary-representation
Finding Set bits and checking if its prime for all values btw left and right
finding-set-bits-and-checking-if-its-pri-4s1l
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sdeepthi035
NORMAL
2024-09-11T13:43:54.485673+00:00
2024-09-11T13:43:54.485695+00:00
73
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public static int numberOfSetBits(int n)\n {\n int cnt=0;\n while(n!=0)\n {\n cnt+=n&1;\n n>>=1;\n }\n return cnt;\n }\n public static int prime(int n)\n {\n if(n<=1)\n return 0;\n for(int i=2;i<n;i++)\n if(n%i==0)\n return 0;\n return 1;\n }\n public int countPrimeSetBits(int left, int right) {\n int cnt=0;\n while(left<=right)\n {\n int n=numberOfSetBits(left);\n cnt+=prime(n);\n left++;\n }\n return cnt;\n\n \n }\n}\n```
1
0
['Java']
0
prime-number-of-set-bits-in-binary-representation
C || C++ || JAVA || PYTHON || 762. Prime Number of Set Bits in Binary Representation
c-c-java-python-762-prime-number-of-set-sndhe
Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1)\n Add your space complexity here, e.g. O(n) \n\n# Code
harithvarakesan
NORMAL
2024-09-03T16:29:08.520327+00:00
2024-09-03T16:29:08.520350+00:00
463
false
# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n int total=0;\n for(int i=left;i<=right;i++){\n int nbits=0;\n int n=i;\n while(n>0){\n if(n%2==1){\n nbits+=1;\n }\n n/=2;\n }\n boolean prime=true;\n if(nbits<=1){\n prime=false;\n }\n for(int j=2;j<=Math.sqrt(nbits);j++){\n if(nbits%j==0){\n prime=false;\n }\n }\n if(prime){\n total+=1;\n }\n }\n return total;\n \n }\n}\n```\n```c++ []\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int total=0;\n for(int i=left;i<=right;i++){\n int nbits=0;\n int n=i;\n while(n>0){\n if(n%2==1){\n nbits+=1;\n }\n n/=2;\n }\n bool prime=true;\n if(nbits<=1){\n prime=false;\n }\n for(int i=2;i<=sqrt(nbits);i++){\n if(nbits%i==0){\n prime=false;\n }\n }\n if(prime){\n total+=1;\n }\n }\n return total;\n \n }\n};\n```\n```python []\nclass Solution(object):\n def countPrimeSetBits(self, left, right):\n total=0\n for i in range(left,right+1):\n nbits=0\n n=i\n while(n>0):\n if(n%2==1):\n nbits+=1\n n/=2\n prime=True\n if(nbits<=1):\n prime=False\n for j in range(2,int(math.sqrt(nbits))+1):\n if(nbits%j==0):\n prime=False\n if(prime):\n total+=1\n return total\n```\n```c []\nint countPrimeSetBits(int left, int right) {\n int total=0;\n for(int i=left;i<=right;i++){\n int nbits=0;\n int n=i;\n while(n>0){\n if(n%2==1){\n nbits+=1;\n }\n n/=2;\n }\n bool prime=true;\n if(nbits<=1){\n prime=false;\n }\n for(int i=2;i<=sqrt(nbits);i++){\n if(nbits%i==0){\n prime=false;\n }\n }\n if(prime){\n total+=1;\n }\n }\n return total;\n}\n```\n
1
0
['Math', 'Bit Manipulation', 'C', 'Python', 'C++', 'Java', 'Python3']
1
prime-number-of-set-bits-in-binary-representation
without built in function brute approach beats 50%
without-built-in-function-brute-approach-ky7e
Intuition\nto understand solution go first study how to find number of setbits .\n\n# Approach\nby doing bitwise and of a number n and (n-1) you can find number
ashmit76
NORMAL
2024-06-15T18:40:33.052785+00:00
2024-06-15T18:40:33.052817+00:00
51
false
# Intuition\nto understand solution go first study how to find number of setbits .\n\n# Approach\nby doing bitwise and of a number n and (n-1) you can find number of set bits . \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isprime(int n ){\n if(n==1)return false ;\n for(int i = 2 ; i <=sqrt(n) ; i++)\n {\n if(n%i==0)return false ;\n }\n return true ; \n }\n int countPrimeSetBits(int left, int right) {\n int count = 0 ;\n for(int i = left ; i<=right ;i++){\n int setbit = 0 ; \n int num = i ;\n while(num>0){\n num = num&(num-1) ; \n setbit++ ; \n }\n if(isprime(setbit))count++;\n }\n return count ;\n }\n};\n```
1
0
['C++']
0
prime-number-of-set-bits-in-binary-representation
C++ easy Solution using Seive of Eratosthenes
c-easy-solution-using-seive-of-eratosthe-vfmb
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Use the sieve of Eratosthenes to precompute whether each number from 0 to 100 is pri
skill_improve
NORMAL
2024-05-01T10:10:20.607694+00:00
2024-05-01T10:10:20.607722+00:00
79
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Use the sieve of Eratosthenes to precompute whether each number from 0 to 100 is prime or not.\n1. For each number in the range [left, right], count the number of set bits (1s) using __builtin_popcount.\n1. Check if the count of set bits is a prime number, and if so, increment the counter.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an array isprime of size 101 to store whether each number from 0 to 100 is prime or not.\n1. Use the sieve of Eratosthenes to mark all composite numbers in the isprime array.\n1. Iterate over the range [left, right] and for each number, count the number of set bits using __builtin_popcount.\n1. Check if the count of set bits is a prime number by checking the isprime array.\n1. If the count is prime, increment the counter.\n1. Finally, return the counter as the result.\n\n# Complexity\n- **Time complexity**:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. Precomputing whether each number from 0 to 100 is prime using the sieve of Eratosthenes takes O(100*log(log(100))) time.\n1. Counting the set bits for each number in the range [left, right] takes O(right - left) time.\n1. Overall, the time complexity is O(right - left) + O(log(log(100))), which simplifies to O(right - left).\n\n- **Space complexity**:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. The space complexity is O(1) since the isprime array has a fixed size of 101, and the additional space used is constant.\n\n# Code\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n bool isprime[101];\n memset(isprime,true,sizeof(isprime));\n isprime[0]=0;\n isprime[1]=0;\n for(int i=2;i*i<=100;i++){\n if(isprime[i]){\n for(int j=i*i;j<=100;j+=i){\n isprime[j]=false;\n }\n }\n }\n for(auto i:isprime){\n cout<<i<<" ";\n }\n cout<<endl;\n int cnt=0;\n for(int i=left;i<=right;i++){\n int x=__builtin_popcount(i);\n if(isprime[x]) cnt++;\n }\n return cnt;\n }\n};\n```\nHappy Coding \uD83D\uDE0A\uD83D\uDE0A\n(\u25CF\'\u25E1\'\u25CF)(\u2741\xB4\u25E1`\u2741)(\u25CF\'\u25E1\'\u25CF)
1
0
['Math', 'Bit Manipulation', 'C++']
1
prime-number-of-set-bits-in-binary-representation
Easy java solution
easy-java-solution-by-vidojevica-27z1
Intuition\nTo solve this problem, we need to count the number of integers with a prime number of set bits in their binary representation within the given range.
vidojevica
NORMAL
2024-04-15T15:07:40.582088+00:00
2024-04-15T15:07:40.582125+00:00
411
false
# Intuition\nTo solve this problem, we need to count the number of integers with a prime number of set bits in their binary representation within the given range.\n\n# Approach\n1.Iterate through each integer in the given range.\n2.Count the number of set bits in the binary representation of each integer.\n3.Check if the count is a prime number or equals to 2 or 3.\n4.Increment the result count accordingly.\n\n# Complexity\n- Time complexity:\nO(n\u22C5loglogn) where n is the range between left and right.\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int countPrimeSetBits(int left, int right) \n {\n int result = 0;\n\n while (left <= right)\n {\n int bitCount = 0;\n int tempLeft = left;\n\n while (tempLeft > 0)\n {\n if (tempLeft % 2 == 1) bitCount++;\n\n tempLeft /= 2;\n }\n\n if (bitCount == 2 || bitCount == 3) result++;\n else if (bitCount != 1)\n {\n boolean prime = true;\n\n for (int i = 2; i <= Math.sqrt(bitCount); i++)\n {\n if (bitCount % i == 0)\n {\n prime = false;\n break;\n }\n }\n\n if (prime) result++;\n } \n \n left++;\n }\n\n return result;\n }\n}\n```
1
0
['Java']
0
prime-number-of-set-bits-in-binary-representation
Simple java code 2 ms beats 97 %
simple-java-code-2-ms-beats-97-by-arobh-kjxe
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n final int[] arr = new int[20]; \n arr[
Arobh
NORMAL
2024-01-16T03:20:44.290250+00:00
2024-01-16T03:20:44.290278+00:00
29
false
\n# Complexity\n- \n![image.png](https://assets.leetcode.com/users/images/afed3731-ca7d-464e-8931-d2cc05a26624_1705375234.7481887.png)\n# Code\n```\nclass Solution {\n public int countPrimeSetBits(int left, int right) {\n final int[] arr = new int[20]; \n arr[2] = 1; arr[3] = 1; arr[5] = 1; arr[7] = 1; \n arr[11] = 1; arr[13] = 1; arr[17] = 1; arr[19] = 1; \n int count = 0; \n while (left <= right) {\n count += arr[Integer.bitCount(left)]; \n left++; \n }\n return count; \n }\n}\n```
1
0
['Java']
0
prime-number-of-set-bits-in-binary-representation
prime-number-of-set-bits-in-binary-representation
prime-number-of-set-bits-in-binary-repre-c3im
Code\n\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n count = 0\n for i in range(left,right + 1):\n
_suraj__007
NORMAL
2023-11-29T14:44:16.761171+00:00
2023-11-29T14:44:16.761197+00:00
258
false
# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n count = 0\n for i in range(left,right + 1):\n a = bin(i)[2:]\n t = a.count("1")\n l = []\n if t==1:\n pass\n else:\n for i in range(2,t):\n if t%i==0:\n break\n else:\n count+=1\n return count\n \n \n\n\n\n\n \n```
1
0
['Python3']
0
prime-number-of-set-bits-in-binary-representation
[C++] || Simple and Easy to Understand Solution || Clean Code
c-simple-and-easy-to-understand-solution-nnxb
\n\n# Code\n\nclass Solution {\npublic:\n\n bool isprime(int x){\n return (x == 2 || x == 3 || x == 5 || x == 7 ||\n x == 11 || x == 13
C0derX
NORMAL
2023-10-03T12:12:12.967471+00:00
2023-10-03T12:12:12.967499+00:00
6
false
\n\n# Code\n```\nclass Solution {\npublic:\n\n bool isprime(int x){\n return (x == 2 || x == 3 || x == 5 || x == 7 ||\n x == 11 || x == 13 || x == 17 || x == 19);\n }\n int countSetBits(int n){\n int cnt=0;\n while(n){\n cnt++;\n n=n&(n-1);\n }\n\n return cnt;\n }\n int countPrimeSetBits(int left, int right) {\n int res=0;\n for(int n=left;n<=right;n++){\n int setBits=0;\n setBits=countSetBits(n);\n if(isprime(setBits))\n res++;\n }\n \n\n return res;\n }\n};\n```
1
0
['Math', 'Bit Manipulation', 'C++']
0
prime-number-of-set-bits-in-binary-representation
Solution with 3 for loop javascript
solution-with-3-for-loop-javascript-by-m-3cj0
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
MentalistTr
NORMAL
2023-08-11T16:02:46.170691+00:00
2023-08-11T16:02:46.170716+00:00
12
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} left\n * @param {number} right\n * @return {number}\n */\nvar countPrimeSetBits = function(left, right) {\n \n if(left < 10000000 && (right - left) <= 100000) { \n \n let result = 0;\n \n for(let i = left;i <=right;i++) {\n \n let asalcheck =true;\n \n let count = 0\n let number = i.toString(2).split(\'\');\n \n for(let j =0;j < number.length;j++) {\n if(number[j] == 1) {\n count++\n }\n \n }\n if(count < 2) {\n asalcheck = false\n }\n \n for(let k = 2;k <= count;k++) {\n \n if(count % k === 0 && count != k ) {\n asalcheck = false;\n }\n }\n \n if(asalcheck === true) {\n result++;\n } \n \n}\n \n return result\n \n}\n};\n```
1
0
['JavaScript']
0
prime-number-of-set-bits-in-binary-representation
C# solution | 70% time, 67.5% space | used set
c-solution-70-time-675-space-used-set-by-wv7y
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(log2(n))\n Add your space complexity here, e.g. O(n) \n
photon_einstein
NORMAL
2023-05-27T02:06:53.545139+00:00
2023-05-27T02:06:53.545172+00:00
453
false
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(log2(n))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int CountPrimeSetBits(int left, int right) {\n int i, maxPrime = 32, step=1, n=0;\n HashSet<int> s = new HashSet<int>();\n for (i = 2; i <= maxPrime; i+=step) {\n if (isPrime(ref i)) {\n s.Add(i);\n }\n if (i == 3) {\n ++step;\n }\n }\n for (i = left; i <= right; ++i) {\n if (s.Contains(binCountBitsOn(ref i))) {\n ++n;\n }\n }\n return n;\n }\n\n public int binCountBitsOn(ref int n) {\n int i, c = 0;\n for (i = 1 << 30; i > 0; i = i / 2) {\n if((n & i) != 0) {\n ++c;\n }\n }\n return c;\n }\n\n public bool isPrime(ref int n) {\n if (n <= 1) {\n return false;\n } else if (n == 2) {\n return true;\n }\n for (int i = 3; i < n; i+=2) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n }\n\n}\n\n\n```
1
0
['C#']
0
prime-number-of-set-bits-in-binary-representation
762. Prime Number of Set Bits in Binary Representation
762-prime-number-of-set-bits-in-binary-r-g7or
\nclass Solution {\npublic:\n bool isPrime(int n){\n bool flag=true;\n if(n==0 || n==1) return false;\n for(int i=2;i*i<=n;i++){\n
pspraneetsehra08
NORMAL
2023-05-23T14:10:24.883901+00:00
2023-05-23T14:10:24.883943+00:00
325
false
```\nclass Solution {\npublic:\n bool isPrime(int n){\n bool flag=true;\n if(n==0 || n==1) return false;\n for(int i=2;i*i<=n;i++){\n if(n%i==0){\n flag=false;\n break;\n }\n }\n return flag;\n }\n int countPrimeSetBits(int left, int right) {\n int res=0,cnt=0;\n for(int i=left;i<=right;i++){\n cnt=0;\n int tmp=i;\n while(tmp>0){\n if(tmp&1) cnt++;\n tmp>>=1;\n }\n if(isPrime(cnt)) res++;\n }\n return res;\n }\n};\n```
1
0
['Bit Manipulation', 'C', 'C++']
0
prime-number-of-set-bits-in-binary-representation
Prime Number of Set Bits in Binary Representation Solution in C++
prime-number-of-set-bits-in-binary-repre-nh32
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
The_Kunal_Singh
NORMAL
2023-02-18T05:31:21.428048+00:00
2023-02-18T05:31:21.428098+00:00
61
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int i, j, k, flag=0, countbits=0, count=0;\n for(i=left ; i<=right ; i++)\n {\n flag=0;\n countbits=0;\n j = i;\n while(j>0)\n {\n k = j%2;\n j = j/2;\n if(k==1)\n {\n countbits++;\n }\n }\n for(j=2 ; j<=countbits/2 ; j++)\n {\n if(countbits%j==0)\n {\n flag=1;\n break;\n }\n }\n if(flag!=1 && countbits>1)\n {\n count++;\n }\n }\n return count;\n }\n};\n```
1
0
['C++']
0
prime-number-of-set-bits-in-binary-representation
JavaScript
javascript-by-ruben_krbashyan-gfko
\n\nvar countPrimeSetBits = function (left, right) {\n // numbers not greater then 10^6 have max 20 set bits\n // primes to check 2, 3, 5, 7, 11, 13, 17,
ruben_krbashyan
NORMAL
2023-01-28T23:50:56.551404+00:00
2023-01-28T23:50:56.551437+00:00
147
false
\n```\nvar countPrimeSetBits = function (left, right) {\n // numbers not greater then 10^6 have max 20 set bits\n // primes to check 2, 3, 5, 7, 11, 13, 17, 19\n \n const primes = [2, 3, 5, 7, 11, 13, 17, 19];\n let count = 0;\n\n for (let i = left; i <= right; i++) {\n const setBitCount = [...i.toString(2)].reduce((s, c) => s + +c, 0);\n if (primes.includes(setBitCount)) count++;\n }\n\n return count;\n};\n```
1
0
['JavaScript']
0
prime-number-of-set-bits-in-binary-representation
easy solution||c++
easy-solutionc-by-himanshukla2003-jyk7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- O(n^2
himanshukla2003
NORMAL
2023-01-08T08:20:15.342482+00:00
2023-01-08T08:20:15.342522+00:00
473
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int l, int r) {\n set<int> p = { 2, 3, 5, 7, 11, 13, 17, 19};// max possible prime no. 19.Because of range is 10^6 \n int x=0;\n while((r-l+1)!=0){\n int i=0;\n int y=l;// here we put the value to y because if you use l as code than value of l change.....\n while(y!=0){\n i+=(y&1);\n y=y>>1;\n }\n x+=p.count(i);\n l++;\n }\n return x;\n }\n};\n```
1
0
['C++']
0
prime-number-of-set-bits-in-binary-representation
✅ [Swift] Easy to understand
swift-easy-to-understand-by-lmvtsv-9e6d
\nclass Solution {\n func countPrimeSetBits(_ left: Int, _ right: Int) -> Int {\n\t var left = left\n\t var result = 0\n\t while left <= right {\n\t
lmvtsv
NORMAL
2022-12-01T13:40:21.127972+00:00
2022-12-01T13:40:21.127994+00:00
66
false
```\nclass Solution {\n func countPrimeSetBits(_ left: Int, _ right: Int) -> Int {\n\t var left = left\n\t var result = 0\n\t while left <= right {\n\t\t result += isPrime(left.nonzeroBitCount) ? 1 : 0\n\t\t left += 1\n\t }\n\t return result\n }\n\n func isPrime(_ number: Int) -> Bool {\n\t return number > 1 && !(2..<number).contains { number % $0 == 0 }\n }\n}\n```
1
0
['Swift']
0
prime-number-of-set-bits-in-binary-representation
Prime Number of Set Bits in Binary Representation || Solution
prime-number-of-set-bits-in-binary-repre-4w2z
\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int count=0;\n for(int i=left;i<=right;++i)\n {\n
SAJAL_2526
NORMAL
2022-10-18T16:55:06.453170+00:00
2022-10-18T16:55:06.453274+00:00
151
false
```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int count=0;\n for(int i=left;i<=right;++i)\n {\n bitset<32> b(i);\n int x=b.count();\n int flag=0;\n if(x==1)\n continue;\n for(int j=2;j<=sqrt(x);++j)\n {\n if(x%j==0)\n {\n flag=1;\n break;\n }\n }\n if(flag==0)\n {\n count++;\n }\n }\n return count;\n }\n};\n```
1
0
['Bit Manipulation', 'C']
0
prime-number-of-set-bits-in-binary-representation
Prime Number of Set Bits in Binary Representation (Python)
prime-number-of-set-bits-in-binary-repre-fowy
I have this problem explained and solved on my channel , please check it out.\nhttps://youtube.com/playlist?list=PLxukZCav2iGzzFMWq-esWbEEZ0KJ17t9L\nalso please
abdullah956
NORMAL
2022-10-16T09:14:55.345364+00:00
2022-10-16T09:17:58.589545+00:00
1,131
false
I have this problem explained and solved on my channel , please check it out.\nhttps://youtube.com/playlist?list=PLxukZCav2iGzzFMWq-esWbEEZ0KJ17t9L\nalso please, give your valueable feedback.\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n def isPrime(n:int)->bool :\n count=0\n for i in range(1,n+1) :\n if n%i==0:\n count+=1\n if count==2 :\n return True\n else:\n return False\n countp=0\n for i in range(left,right+1) :\n ans = bin(i).count("1")\n if isPrime(ans) :\n countp+=1\n return countp\n```
1
0
['Python']
0
prime-number-of-set-bits-in-binary-representation
C++ | Setbit Count | Easy Code
c-setbit-count-easy-code-by-ankit4601-exur
Please Upvote :)\n\n\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int res=0;\n for(int i=left;i<=right;i++)\n
ankit4601
NORMAL
2022-08-22T17:56:25.813261+00:00
2022-08-22T17:56:25.813295+00:00
485
false
Please Upvote :)\n\n```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int res=0;\n for(int i=left;i<=right;i++)\n {\n if(check(bits(i)))\n res++;\n }\n return res;\n }\n int check(int n)\n {\n if(n<2)\n return 0;\n for(int i=2;i<=sqrt(n);i++)\n {\n if(n%i==0)\n return 0;\n }\n return 1;\n }\n int bits(int n)\n {\n int c=0;\n while(n)\n {\n c+=n%2;\n n/=2;\n }\n return c;\n }\n};\n```
1
0
['Bit Manipulation', 'C', 'C++']
0
prime-number-of-set-bits-in-binary-representation
Almighty C++
almighty-c-by-nitinkumar12577-fszm
\tint countSetBits(int n)\n\t\t{\n\t\t\tint count = 0;\n\t\t\twhile(n!=0)\n\t\t\t{\n\t\t\t\tn = n&(n-1);\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\treturn count;\n\t\t}\
nitinkumar12577
NORMAL
2022-08-06T09:50:53.022464+00:00
2022-08-06T09:51:19.564363+00:00
243
false
\tint countSetBits(int n)\n\t\t{\n\t\t\tint count = 0;\n\t\t\twhile(n!=0)\n\t\t\t{\n\t\t\t\tn = n&(n-1);\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\treturn count;\n\t\t}\n \n bool isPrime(int n)\n {\n if(n==2 || n==3 || n==5 || n==7 || n==11 || n==13 || n==17 || n==19 || n==23 || n==29)\n return true;\n \n return false;\n }\n\n \n int countPrimeSetBits(int left, int right)\n {\n \n int i,count = 0;\n for(i=left;i<=right;i++)\n {\n if(isPrime(countSetBits(i)))\n {\n count++;\n }\n }\n \n return count;\n }\n
1
0
['C']
0
prime-number-of-set-bits-in-binary-representation
C++ || 100% fast || 100% less memory usage
c-100-fast-100-less-memory-usage-by-van_-t1qq
\nclass Solution {\npublic:\n bool isPrimary(int n){\n if(n <= 1) return false;\n for(int i = 2; i<=n/2; i++){\n if(n%i == 0) return
van_astrea
NORMAL
2022-07-31T11:18:19.873928+00:00
2022-07-31T11:18:19.873972+00:00
235
false
```\nclass Solution {\npublic:\n bool isPrimary(int n){\n if(n <= 1) return false;\n for(int i = 2; i<=n/2; i++){\n if(n%i == 0) return false;\n }\n return true;\n }\n \n int countBits(int n){\n int x = 0;\n while(n>0){\n n = n & (n-1);\n x++;\n }\n return x;\n }\n \n int countPrimeSetBits(int left, int right) {\n int count = 0;\n for(int i = left; i<=right; i++){\n if(isPrimary(countBits(i))) count++;\n }\n return count;\n }\n};\n```
1
0
['C']
0
prime-number-of-set-bits-in-binary-representation
Python | Easy and Fast
python-easy-and-fast-by-aryonbe-k418
```\nimport math\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n primes = set()\n for i in range(2, 30):\n
aryonbe
NORMAL
2022-07-11T05:53:08.205818+00:00
2022-07-11T05:53:08.205865+00:00
213
false
```\nimport math\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n primes = set()\n for i in range(2, 30):\n for p in primes:\n if i%p == 0: break\n else:\n primes.add(i)\n res = 0\n for i in range(left, right+1):\n if bin(i).count(\'1\') in primes:\n res += 1\n return res
1
0
['Python']
0
prime-number-of-set-bits-in-binary-representation
A faster solution | O(4*log(r)*log(r)) | 0ms | Digit DP | C++
a-faster-solution-o4logrlogr-0ms-digit-d-qktj
Wrote a digit dp solution out of boredom.\nPrecautionary advice for beginners : It is okay if you don\'t understand this solution right now. This code is optima
suraj__k
NORMAL
2022-07-01T15:52:46.859957+00:00
2022-07-10T04:29:47.412334+00:00
185
false
Wrote a digit dp solution out of boredom.\nPrecautionary advice for beginners : It is okay if you don\'t understand this solution right now. This code is optimal for higher constraints on R-L (like 1e18), where we can not traverse from L to R for optimal solution.\n\nConvert both left and right to their binary representation as strings. After that count all the strings that exist (lexicographcally) between a and b (both inclusive) and end up having prime number of set bits that is \'1\'s.\n\n**Similar Problem**\nhttps://leetcode.com/problems/find-all-good-strings/\n\n**Code**\n```\nclass Solution {\npublic:\n vector <int> prime;\n \n int memo[32][2][2][32];\n \n int helper(string &a, string &b, int i, int down, int up, int cnt)\n {\n if(i >= a.size())\n {\n if(prime[cnt]==1)\n return 1;\n return 0;\n }\n \n if(memo[i][down][up][cnt] != -1) return memo[i][down][up][cnt]; \n \n int ans = 0;\n \n int low = 0;\n int high = 1;\n \n if(!down)\n low = a[i]-\'0\';\n \n if(!up)\n high = b[i]-\'0\';\n \n for(int j = low; j <= high; j++)\n {\n ans += helper(a,b,i+1,down||(j > low), up||(j < high), cnt + (j==1));\n }\n \n return memo[i][down][up][cnt] = ans;\n }\n \n int countPrimeSetBits(int left, int right) {\n \n string a,b;\n markPrimes();\n \n while(left)\n {\n a += \'0\' + left%2;\n left/=2;\n }\n \n while(right)\n {\n b += \'0\' + right%2;\n right/=2;\n }\n \n while(a.size() < 31)\n a += \'0\';\n \n while(b.size() < 31)\n b += \'0\';\n \n reverse(a.begin(), a.end());\n reverse(b.begin(), b.end());\n \n memset(memo,-1,sizeof memo);\n int ans = helper(a,b,0,0,0,0);\n return ans;\n }\n \n void markPrimes()\n {\n prime.resize(33,0);\n prime[2] = 1;\n prime[3] = 1;\n prime[5] = 1;\n prime[7] = 1;\n prime[11] = 1;\n prime[13] = 1;\n prime[17] = 1;\n prime[19] = 1;\n prime[23] = 1;\n prime[29] = 1;\n prime[31] = 1;\n }\n};\n```\n\nTime complexity : O(4* log(r)* log(r))\nSpace complexity : O(4* log(r)* log(r))
1
0
['Dynamic Programming', 'Recursion', 'Memoization', 'C']
0
prime-number-of-set-bits-in-binary-representation
C++ solution with Brian Kernighan’s Algorithm
c-solution-with-brian-kernighans-algorit-gupy
\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) \n {\n vector<bool> prime(20, false);\n prime[2] = prime[3] = prime
osmanay
NORMAL
2022-06-19T16:47:58.715827+00:00
2022-06-19T16:47:58.715876+00:00
132
false
```\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) \n {\n vector<bool> prime(20, false);\n prime[2] = prime[3] = prime[5] = prime[7] = prime[11] = prime[13] = prime[17] = prime[19] = true;\n \n int res = 0;\n \n for(int i=left; i<=right; i++)\n {\n int cnt = 0;\n int num = i;\n while(num)\n {\n num = num & (num-1);\n cnt++;\n }\n \n res += prime[cnt];\n }\n \n return res;\n }\n};\n```
1
0
[]
1
prime-number-of-set-bits-in-binary-representation
java || simple solution || easy to understand
java-simple-solution-easy-to-understand-2vqhh
class Solution {\n boolean prime(int n)\n {\n int i,c=0;\n for(i=1;i<=n;i++)\n {\n if(n%i==0)c++;\n }\n if(c
solver-01
NORMAL
2022-05-22T10:50:43.263081+00:00
2022-05-22T10:50:43.263115+00:00
23
false
class Solution {\n boolean prime(int n)\n {\n int i,c=0;\n for(i=1;i<=n;i++)\n {\n if(n%i==0)c++;\n }\n if(c==2){\n return true;\n }\n else{\n return false;\n }\n }\n public int countPrimeSetBits(int left, int right) {\n int i,c=0,k;\n for(i=left;i<=right;i++)\n {\n k=Integer.bitCount(i);\n boolean yes=prime(k);\n if(yes==true)c++;\n }\n return c;\n }\n}
1
0
[]
0
prime-number-of-set-bits-in-binary-representation
C++ O((log N) ^ 2) Solution (0ms)
c-olog-n-2-solution-0ms-by-stingxp-n2bk
Main idea\n\nGiven a = 10101001, we can count the number of positive integers less than a with 5 bits set as follows:\n\n1. Count b\'s such that b = 0xxxxxxx an
stingxp
NORMAL
2022-04-29T09:32:23.585149+00:00
2022-04-29T12:54:43.136427+00:00
70
false
# Main idea\n\nGiven `a = 10101001`, we can count the number of positive integers less than `a` with 5 bits set as follows:\n\n1. Count `b`\'s such that `b = 0xxxxxxx` and there are 5 bits set in `x`\'s.\n\t- There are <img src="https://render.githubusercontent.com/render/math?math=7\\choose5"> such `b`\'s.\n1. Count `b`\'s such that `b = 100xxxxx` and there are 4 bits set in `x`\'s.\n\t- There are <img src="https://render.githubusercontent.com/render/math?math=5\\choose4"> such `b`\'s.\n1. Count `b`\'s such that `b = 10100xxx` and there are 3 bits set in `x`\'s.\n\t- There are <img src="https://render.githubusercontent.com/render/math?math=3\\choose3"> such `b`\'s.\n1. Count `b`\'s such that `b = 10101000` and there are 2 bits set in `x`\'s.\n - There are 0 such `b`\'s.\n\nLet\'s say `until(n, p)` counts the number of positive integers less than `n` with `p` bits set.\nThen, we only need to compute `until(right + 1, p) - until(left, p)` for each valid `p`.\n\n# Complexity\n\nLet\'s say `N = right`.\n\n- Computing Pascal\'s triangle requires <img src="https://render.githubusercontent.com/render/math?math=O((\\log N)^2)"> operations.\n- Computing primes takes <img src="https://render.githubusercontent.com/render/math?math=O((\\log N)(\\log \\log \\log N))"> (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithmic_complexity).\n\t- Here I omitted prime computation in the code snippet below.\n- Computing the count for all valid primes takes <img src="https://render.githubusercontent.com/render/math?math=O((\\log N)^2)">\n\t- Asymptotically there are <img src="https://render.githubusercontent.com/render/math?math=O(\\log N)"> primes in a range [1, N] (https://en.wikipedia.org/wiki/Prime_number_theorem).\n\t- `until` function takes <img src="https://render.githubusercontent.com/render/math?math=O(\\log N)">.\n\nTherefore, the time complexity is <img src="https://render.githubusercontent.com/render/math?math=O((\\log N)^2)">.\n\n\n# Code snippet\n```c++\nclass Solution {\npublic:\n int countPrimeSetBits(int l, int r) {\n // Build Pascal\'s triangle\n // O((log r) ^ 2)\n for (int i = 0; i < 21; ++i) {\n for (int j = 0; j <= i; ++j) {\n if (j == 0 || j == i) {\n comb[i][j] = 1;\n } else {\n comb[i][j] = comb[i-1][j-1] + comb[i-1][j]; \n }\n }\n } \n\n // O((log r) ^ 2), as the ratio of primes converges to log r.\n int ret = 0;\n for (auto p : {2, 3, 5, 7, 11, 13, 17, 19}) {\n ret += until(r+1, p) - until(l, p);\n }\n return ret;\n }\n \n // O(log n)\n int until(int n, int p) {\n string s;\n for (int nn = n; nn > 0; nn >>= 1) {\n s.push_back(nn & 1);\n }\n \n int ret = 0;\n while (!s.empty()) {\n if (s.back() == 1) {\n ret += pascal(s.size()-1, p);\n --p;\n }\n s.pop_back();\n }\n return ret;\n }\n \n int pascal(int a, int b) {\n if (a < 0 || b < 0 || a < b) {\n return 0;\n } else {\n return comb[a][min(b, a-b)];\n }\n }\n \n int comb[21][21];\n};\n```
1
0
[]
0
prime-number-of-set-bits-in-binary-representation
Easy || C++ || Kernighan's Algorithm || Explained
easy-c-kernighans-algorithm-explained-by-wfci
class Solution {\npublic:\n\t\n\t/\n\t\t=>Idea is to find the no of set bits of interget i which is in range [left,right] inclusive\n\t\t=>so to calculate no. o
its_Dark_
NORMAL
2022-04-15T09:34:11.476453+00:00
2022-04-15T09:52:07.332272+00:00
54
false
class Solution {\npublic:\n\t\n\t*/\n\t\t=>Idea is to find the no of set bits of interget i which is in range [left,right] inclusive\n\t\t=>so to calculate no. of set bits \n\t\t\t\t=>we find the right most set bit everytime and subtrract that from the orgnal no. untill the orignal no. is greater than 0\n\t\t\t\t=>check how many time this iteration is done, that turns out to be setbits\n\t\t=>Atlast if the no. of set bits are prime increment the answer.\n\t*/\n\t\n bool isprime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} \n int countPrimeSetBits(int left, int right) {\n int ans=0;\n for(int i=left;i<=right;i++){\n int cnt=0;\n int x=i;\n while(x>0){\n int rsb=x&(-x);\n x=x-rsb;\n cnt++;\n }\n if(isprime(cnt))ans++;\n }\n return ans;\n }\n};
1
0
[]
0
combinations
Short Iterative C++ Answer 8ms
short-iterative-c-answer-8ms-by-hengyi-xtma
class Solution {\n public:\n \tvector<vector<int>> combine(int n, int k) {\n \t\tvector<vector<int>> result;\n \t\tint i = 0;\n \t\tvector<int> p
hengyi
NORMAL
2015-10-09T05:47:58+00:00
2018-10-26T05:21:48.708530+00:00
53,751
false
class Solution {\n public:\n \tvector<vector<int>> combine(int n, int k) {\n \t\tvector<vector<int>> result;\n \t\tint i = 0;\n \t\tvector<int> p(k, 0);\n \t\twhile (i >= 0) {\n \t\t\tp[i]++;\n \t\t\tif (p[i] > n) --i;\n \t\t\telse if (i == k - 1) result.push_back(p);\n \t\t\telse {\n \t\t\t ++i;\n \t\t\t p[i] = p[i - 1];\n \t\t\t}\n \t\t}\n \t\treturn result;\n \t}\n };
477
7
[]
52
combinations
Backtracking Solution Java
backtracking-solution-java-by-fabrizio3-8ntr
public static List<List<Integer>> combine(int n, int k) {\n \t\tList<List<Integer>> combs = new ArrayList<List<Integer>>();\n \t\tcombine(combs, new A
fabrizio3
NORMAL
2015-04-10T09:15:05+00:00
2018-10-26T09:09:57.632221+00:00
99,425
false
public static List<List<Integer>> combine(int n, int k) {\n \t\tList<List<Integer>> combs = new ArrayList<List<Integer>>();\n \t\tcombine(combs, new ArrayList<Integer>(), 1, n, k);\n \t\treturn combs;\n \t}\n \tpublic static void combine(List<List<Integer>> combs, List<Integer> comb, int start, int n, int k) {\n \t\tif(k==0) {\n \t\t\tcombs.add(new ArrayList<Integer>(comb));\n \t\t\treturn;\n \t\t}\n \t\tfor(int i=start;i<=n;i++) {\n \t\t\tcomb.add(i);\n \t\t\tcombine(combs, comb, i+1, n, k-1);\n \t\t\tcomb.remove(comb.size()-1);\n \t\t}\n \t}
387
8
['Backtracking', 'Java']
71
combinations
【Video】Simple Backtracking Solution
video-simple-backtracking-solution-by-ni-ug0h
Intuition\nUsing backtracking to create all possible combinations.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/oDn_6n0ahkM\n\n## Subscribe to my channel from
niits
NORMAL
2024-07-05T02:25:06.239282+00:00
2024-07-05T02:25:06.239315+00:00
17,047
false
# Intuition\nUsing backtracking to create all possible combinations.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/oDn_6n0ahkM\n\n## Subscribe to my channel from here\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Create an empty list `res` to store the final combinations and an empty list `comb` to store the current combination being formed.\n\n2. Define a recursive function `backtrack(start)`, which will generate all possible combinations of size `k` from the numbers starting from `start` up to `n`.\n\n3. In the `backtrack` function:\n - If the length of `comb` becomes equal to `k`, it means we have formed a valid combination, so we append a copy of the current `comb` list to the `res` list. We use `comb[:]` to create a copy of the list since lists are mutable in Python, and we want to preserve the combination at this point without being modified later.\n\n - If the length of `comb` is not equal to `k`, we continue the recursion.\n \n4. Within the `backtrack` function, use a loop to iterate over the numbers starting from `start` up to `n`.\n - For each number `num` in the range, add it to the current `comb` list to form the combination.\n \n - Make a recursive call to `backtrack` with `start` incremented by 1. This ensures that each number can only be used once in each combination, avoiding duplicate combinations.\n\n - After the recursive call, remove the last added number from the `comb` list using `comb.pop()`. This allows us to backtrack and try other numbers for the current position in the combination.\n\n5. Start the recursion by calling `backtrack(1)` with `start` initially set to 1, as we want to start forming combinations with the numbers from 1 to `n`.\n\n6. After the recursion is complete, the `res` list will contain all the valid combinations of size `k` formed from the numbers 1 to `n`. Return `res` as the final result.\n\nThe code uses a recursive backtracking approach to generate all the combinations efficiently. It explores all possible combinations, avoiding duplicates and forming valid combinations of size `k`. The result `res` will contain all such combinations at the end.\n\n# Complexity\n- Time complexity: O(n * k)\nn is the number of elements and k is the size of the subset. The backtrack function is called n times, because there are n possible starting points for the subset. For each starting point, the backtrack function iterates through all k elements. This is because the comb list must contain all k elements in order for it to be a valid subset.\n\n- Space complexity: O(k)\nThe comb list stores at most k elements. This is because the backtrack function only adds elements to the comb list when the subset is not yet complete.\n\n```python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n res = []\n comb = []\n\n def backtrack(start):\n if len(comb) == k:\n res.append(comb[:])\n return\n \n for num in range(start, n + 1):\n comb.append(num)\n backtrack(num + 1)\n comb.pop()\n\n backtrack(1)\n return res\n```\n```javascript []\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function(n, k) {\n const res = [];\n const comb = [];\n\n function backtrack(start) {\n if (comb.length === k) {\n res.push([...comb]);\n return;\n }\n\n for (let num = start; num <= n; num++) {\n comb.push(num);\n backtrack(num + 1);\n comb.pop();\n }\n }\n\n backtrack(1);\n return res; \n};\n```\n```java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> res = new ArrayList<>();\n List<Integer> comb = new ArrayList<>();\n\n backtrack(1, comb, res, n, k);\n return res;\n }\n\n private void backtrack(int start, List<Integer> comb, List<List<Integer>> res, int n, int k) {\n if (comb.size() == k) {\n res.add(new ArrayList<>(comb));\n return;\n }\n\n for (int num = start; num <= n; num++) {\n comb.add(num);\n backtrack(num + 1, comb, res, n, k);\n comb.remove(comb.size() - 1);\n }\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n std::vector<std::vector<int>> res;\n std::vector<int> comb;\n\n backtrack(1, comb, res, n, k);\n return res; \n }\n\nprivate:\n void backtrack(int start, std::vector<int>& comb, std::vector<std::vector<int>>& res, int n, int k) {\n if (comb.size() == k) {\n res.push_back(comb);\n return;\n }\n\n for (int num = start; num <= n; num++) {\n comb.push_back(num);\n backtrack(num + 1, comb, res, n, k);\n comb.pop_back();\n }\n } \n};\n```\n
318
0
['C++', 'Java', 'Python3', 'JavaScript']
1
combinations
Backtracking cheatsheet + simple solution
backtracking-cheatsheet-simple-solution-xa1a0
Backtracking\nBacktracking is a general algorithm for finding all (or some) solutions to some computational problems which incrementally builds candidates to th
sahana__63
NORMAL
2020-09-13T04:34:27.664557+00:00
2020-09-13T08:09:12.922708+00:00
40,199
false
### Backtracking\nBacktracking is a general algorithm for finding all (or some) solutions to some computational problems which incrementally builds candidates to the solution and abandons a candidate ("backtracks") as soon as it determines that the candidate cannot lead to a valid solution. \n\nIt is due to this backtracking behaviour, the backtracking algorithms are often much faster than the brute-force search algorithm, since it eliminates many unnecessary exploration. \n\n```\ndef backtrack(candidate):\n if find_solution(candidate):\n output(candidate)\n return\n \n # iterate all possible candidates.\n for next_candidate in list_of_candidates:\n if is_valid(next_candidate):\n # try this partial candidate solution\n place(next_candidate)\n # given the candidate, explore further.\n backtrack(next_candidate)\n # backtrack\n remove(next_candidate)\n```\n\nOverall, the enumeration of candidates is done in two levels: \n1) at the first level, the function is implemented as recursion. At each occurrence of recursion, the function is one step further to the final solution. \n2) as the second level, within the recursion, we have an iteration that allows us to explore all the candidates that are of the same progress to the final solution. \n\n### Code\nHere we have to explore all combinations of numbers from 1 to n of length k. Indeed, we could solve the problem with the paradigm of backtracking.\n\nProblem - combinations\nDecision space- numbers from 1 to n without repetation\nOutput- all combinatins of numbers from 1 to n of size k\n\n**Python 3**\n```\ndef combine(self, n, k): \n\t\tsol=[]\n def backtrack(remain,comb,nex):\n\t\t\t# solution found\n if remain==0:\n sol.append(comb.copy())\n else:\n\t\t\t\t# iterate through all possible candidates\n for i in range(nex,n+1):\n\t\t\t\t\t# add candidate\n comb.append(i)\n\t\t\t\t\t#backtrack\n backtrack(remain-1,comb,i+1)\n\t\t\t\t\t# remove candidate\n comb.pop()\n \n backtrack(k,[],1)\n return sol\n```\n- Given an empty array, the task is to add numbers between 1 to n to the array upto size of k. We could model the each step to add a number as a recursion function (i.e. backtrack() function).\n\n- At each step, technically we have 9 candidates at hand to add to the array. Yet, we want to consider solutions that lead to a valid case (i.e. is_valid(candidate)). Here the validity is determined by whether the number is repeated or not. Since in the loop, we iterate from nex to n+1, the numbers before nex are already visited and cannot be added to the array. Hence, we dont arrive at an invalid case.\n\n- Then, among all the suitable candidates, we add different numbers using `comb.append(i)` i.e. place(next_candidate). Later we can revert our decision with `comb.pop()` i.e. remove(next_candidate), so that we could try out the other candidates.\n\n- The backtracking would be triggered at the points where the decision space is complete i.e. `nex` is 9 or when the size of the` comb `array becomes` k`. At the end of the backtracking, we would enumerate all the possible combinations.\n\n### Practice problems on backtracking\n*Easy*\n\n[Binary watch](http://)\n\n*Medium*\n\n[Permutations](http://)\n[Permutations II](http://)\n[Combination sum III](http://)\n\n*Hard*\n\n[N Queens](http://)\n[N Queen II](http://)\n[Sudoku solver](http://)\n\n**Notes**\n* For more examples and detailed explanation refer [Recursion II](http://)\n* Any suggestions are welcome.\n
282
0
['Backtracking', 'Python', 'Python3']
14
combinations
1-liner, 3-liner, 4-liner
1-liner-3-liner-4-liner-by-stefanpochman-hp5q
Library - AC in 64 ms\n\nFirst the obvious solution - Python already provides this functionality and it's not forbidden, so let's take advantage of it.\n\n f
stefanpochmann
NORMAL
2015-05-24T02:24:28+00:00
2018-09-08T13:29:54.894018+00:00
36,102
false
**Library - AC in 64 ms**\n\nFirst the obvious solution - Python already provides this functionality and it's not forbidden, so let's take advantage of it.\n\n from itertools import combinations\n \n class Solution:\n def combine(self, n, k):\n return list(combinations(range(1, n+1), k))\n\n---\n\n**Recursive - AC in 76 ms**\n\nBut doing it yourself is more interesting, and not that hard. Here's a recursive version.\n\n class Solution:\n def combine(self, n, k):\n if k == 0:\n return [[]]\n return [pre + [i] for i in range(k, n+1) for pre in self.combine(i-1, k-1)]\n\nThanks to @boomcat for [pointing out](https://discuss.leetcode.com/post/242007) `to use range(k, n+1)` instead of my original `range(1, n+1)`.\n\n---\n\n**Iterative - AC in 76 ms**\n\nAnd here's an iterative one. \n\n class Solution:\n def combine(self, n, k):\n combs = [[]]\n for _ in range(k):\n combs = [[i] + c for c in combs for i in range(1, c[0] if c else n+1)]\n return combs\n\n---\n\n**Reduce - AC in 76 ms**\n\nSame as that iterative one, but using `reduce` instead of a loop:\n\n class Solution:\n def combine(self, n, k):\n return reduce(lambda C, _: [[i]+c for c in C for i in range(1, c[0] if c else n+1)],\n range(k), [[]])
234
24
['Python']
43
combinations
Clear and simple explanation with intuition: 100% faster
clear-and-simple-explanation-with-intuit-fejs
Intuition: Since we are asked to calculate all the possible combinations , hence we have to use backtracking\n\nConcept: In every backtracking problem , there a
thisisakshat
NORMAL
2021-04-04T08:12:20.505067+00:00
2021-04-04T10:10:25.809782+00:00
16,979
false
**Intuition:** Since we are asked to calculate all the possible combinations , hence we have to use backtracking\n\n**Concept:** In every backtracking problem , there are two things to keep in mind , which we will explore here as well :\n* Base Case: Every problem of backtracking has some base case which tells us at which point we have to stop with the recursion process. In our case, when the size of our array `current` equals to `k` i.e. `current.size()=k`, we stop with the recursion and add it to our final result `ans`.\n\n* Conditions: There is just one thing to keep in mind here:\n After generating combinations corresponding to a particular number `i` , proceed to the next element by popping the element from the temporary array `current`, as we used that already. \n \nWe basically consider a number `i`, generate the combinations corresponding to it by recursively calling it again, and then we pop that element as we are done with it and proceed to the next!!\n\t\t\nAnd thats it!! We are done!! Keeping this in mind, here is the code\n\n**Code:**\n```\nclass Solution {\npublic:\n vector<vector<int>> ans;\n \n void helper(int idx, int k,vector<int>&current,int n)\n {\n if(current.size()==k) // base case\n {\n ans.push_back(current);\n return;\n }\n \n for(int i=idx;i<n+1;i++)\n {\n current.push_back(i); //consider the current element i\n helper(i+1,k,current,n); // generate combinations\n current.pop_back(); //proceed to next element\n }\n }\n \n vector<vector<int>> combine(int n, int k) {\n vector<int>current;\n helper(1,k,current,n);\n return ans; //return answer\n }\n};\n```\n**For similar problems: [Backtracking Collection](https://leetcode.com/discuss/interview-question/1141947/backtracking-study-and-analysis)**\n\nIf you like, please **UPVOTE**
186
0
['Backtracking', 'Recursion', 'C', 'C++']
14
combinations
A short recursive Java solution based on C(n,k)=C(n-1,k-1)+C(n-1,k)
a-short-recursive-java-solution-based-on-j0y8
Basically, this solution follows the idea of the mathematical formula C(n,k)=C(n-1,k-1)+C(n-1,k).\n\nHere C(n,k) is divided into two situations. Situation one,
vision57
NORMAL
2015-04-22T14:30:33+00:00
2015-04-22T14:30:33+00:00
30,543
false
Basically, this solution follows the idea of the mathematical formula C(n,k)=C(n-1,k-1)+C(n-1,k).\n\nHere C(n,k) is divided into two situations. Situation one, number n is selected, so we only need to select k-1 from n-1 next. Situation two, number n is not selected, and the rest job is selecting k from n-1.\n\n public class Solution {\n public List<List<Integer>> combine(int n, int k) {\n if (k == n || k == 0) {\n List<Integer> row = new LinkedList<>();\n for (int i = 1; i <= k; ++i) {\n row.add(i);\n }\n return new LinkedList<>(Arrays.asList(row));\n }\n List<List<Integer>> result = this.combine(n - 1, k - 1);\n result.forEach(e -> e.add(n));\n result.addAll(this.combine(n - 1, k));\n return result;\n }\n }
136
5
[]
22
combinations
3 ms Java Solution
3-ms-java-solution-by-anshu2-a2fj
public class Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n
anshu2
NORMAL
2015-12-30T02:46:47+00:00
2018-10-24T10:53:05.383434+00:00
14,340
false
public class Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n if (k > n || k < 0) {\n return result;\n }\n if (k == 0) {\n result.add(new ArrayList<Integer>());\n return result;\n }\n result = combine(n - 1, k - 1);\n for (List<Integer> list : result) {\n list.add(n);\n }\n result.addAll(combine(n - 1, k));\n return result;\n }\n }
135
2
['Java']
15
combinations
A template to those combination problems
a-template-to-those-combination-problems-4w10
Template first.\nAll those combination problems share a common characteristic: either select the element at current position or not, and continue the same proce
zefengsong
NORMAL
2017-07-29T09:27:46.846000+00:00
2017-07-29T09:27:46.846000+00:00
9,619
false
**Template first.**\nAll those combination problems share a common characteristic: either select the element at current position or not, and continue the same process to the next position. Therefore, I summarized a simple template to those problems.\n```\nvector<vector<int>> main(...){\n vector<vector<int>>res; // Store the result, could be other container\n backtrack(res, ...); // Recursion function to fill the res\n return res;\n}\n\nvoid backtrack(vector<vector<int>>& res, int cur, ..., vector<int>vec){\n if(meet the end critria, i.e. cur reach the end of array){ \n //vec could be a certain path/combination/subset\n res.push_back(vec);\n return;\n }\n // Current element is not selected\n backtrack(res, cur+1, ..., vec);\n // Current element is selected\n vec.push_back(cur); // or could be vec.push_back(nums[cur]), vec.push_back(graph[cur]);\n backtrack(res,cur+1, ..., vec);\n}\n```\n***\nNow go back to this problem([LeetCode 77. Combinations](https://leetcode.com/problems/combinations/description/)), we are asked to return all possible combinations of k numbers out of 1 ... n.\nWe start from `1`, if `1` is selected, `k = k-1`; if `1` is not selected, `k = k`; proceed to next number, until `k` becomes `0` - the end critria.\n**Code:**\n```\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>>res;\n backtrack(res,1,n,k,vector<int>());\n return res;\n }\n \n void backtrack(vector<vector<int>>& res, int cur, int n, int k, vector<int>comb){\n if(k==0){\n res.push_back(comb);\n return;\n }\n // If cur>n-k, there are not enough numbers left, we have to select the current element\n if(cur<=n-k) backtrack(res,cur+1,n,k,comb); \n comb.push_back(cur);\n backtrack(res,cur+1,n,k-1,comb);\n }\n```\nOr start with number `n`, and decreasing.\n```\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>>res;\n backtrack(res,n,k,vector<int>());\n return res;\n }\n \n void backtrack(vector<vector<int>>& res, int n, int k, vector<int>comb){\n if(k==0){\n res.push_back(comb);\n return;\n }\n if(n>k) backtrack(res,n-1,k,comb);\n comb.push_back(n);\n backtrack(res,n-1,k-1,comb);\n }\n```\n***\nHere is another combination problem, [LeetCode 78. Subsets](https://leetcode.com/problems/subsets/description/): Given a set of distinct integers, nums, return all possible subsets.\nWe can use this template as well, pretty much the same code.\n```\n vector<vector<int>> subsets(vector<int>& nums) {\n vector<vector<int>>res;\n backtrack(nums,0,vector<int>(),res);\n return res;\n }\n \n void backtrack(vector<int>& nums, int k,vector<int>subset,vector<vector<int>>& res){\n if(k==nums.size()){\n res.push_back(subset);\n return;\n }\n backtrack(nums,k+1,subset,res);\n subset.push_back(nums[k]);\n backtrack(nums,k+1,subset,res);\n }\n```\n***\nStill, I think the template may have room to improve, it costs too much memory.\nOne way to solve it is to change `vector<int>vec` to `vector<int>&vec`, and add `vec.pop_back()` at the end of `backtrack()`, but it may increase the time complexity, don't know which one is better.\n\n***\n**EDIT(8/1/2017)**: Just found another combination problem, [LeetCode 93. Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/description/): Given a string containing only digits, restore it by returning all possible valid IP address combinations.\n\nFor example:\nGiven "25525511135",\n\nreturn ["255.255.11.135", "255.255.111.35"].\n\nCan be easily solved using template:\n\n```\n vector<string> restoreIpAddresses(string s) {\n vector<string> res;\n backtrack(res, s, 0, "", 0);\n return res;\n }\n \n void backtrack(vector<string>& res, string s, int pos, string comb, int num){\n if(num > 4) return; // IP address only allows for 4 segments\n if(pos >= s.size()){\n if(num == 4){\n comb.pop_back();\n res.push_back(comb);\n }\n return;\n }\n // 3 digit\n if(s[pos] != '0' && pos < s.size()-2 && stoi(s.substr(pos,3)) < 256)\n backtrack(res, s, pos + 3, comb + s.substr(pos,3) + ".", num + 1);\n // 2 digit\n if(s[pos] != '0' && pos < s.size()-1)\n backtrack(res, s, pos + 2, comb + s.substr(pos,2) + ".", num + 1);\n // 1 digit\n backtrack(res, s, pos + 1, comb + s.substr(pos,1) + ".", num + 1);\n }\n```\n***\n**Update(8/3/2017):** [131. Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/description/) : Given a string s, partition s such that every substring of the partition is a palindrome. Solution: \n```\n vector<vector<string>> partition(string s) {\n vector<vector<string>>res;\n backtrack(res,s,0,vector<string>());\n return res;\n }\n \n void backtrack(vector<vector<string>>& res, string s, int pos, vector<string> comb){\n if(pos >= s.size()){\n res.push_back(comb);\n return;\n }\n // Palindrome length == 1\n comb.push_back(s.substr(pos,1));\n backtrack(res, s, pos + 1, comb);\n comb.pop_back();\n // Palindrome length > 1\n for(int step = 2; pos + step <= s.size(); step++){\n if(isPalindrome(s.substr(pos, step))){\n comb.push_back(s.substr(pos, step));\n backtrack(res, s, pos + step, comb);\n comb.pop_back();\n }\n }\n }\n \n bool isPalindrome(string s){\n int i(0), j(s.size()-1);\n while(i < j) \n if(s[i++] != s[j--]) return false;\n return true;\n }\n```
127
1
['C++']
6
combinations
🧩 Iterative & Backtracking [VIDEO] 100% Efficient Combinatorial Generation
iterative-backtracking-video-100-efficie-1n77
Intuition\nGiven two integers n and k, the task is to generate all possible combinations of k numbers from the range [1, n]. The initial intuition to solve this
vanAmsen
NORMAL
2023-08-01T00:29:29.083218+00:00
2023-08-01T03:00:46.966797+00:00
17,300
false
# Intuition\nGiven two integers `n` and `k`, the task is to generate all possible combinations of `k` numbers from the range `[1, n]`. The initial intuition to solve this problem is to leverage the concept of combination generation, where we iteratively choose `k` numbers from `n` numbers without any repetition. However, there are multiple approaches to achieve this, and in this analysis, we\'ll be comparing two of them: **backtracking** and **iterative** generation. \n\n# Video - Backtracking\nhttps://youtu.be/aXgNccfxlkA\n\n# Video - Iterative\nhttps://youtu.be/7Ocr2RXNIC4\n\n# Approaches - Summary\nWe\'ll tackle this problem using two distinct methods. The first method utilizes a classic backtracking algorithm, which involves building up a solution incrementally. The second method employs an iterative algorithm, which efficiently generates combinations in lexicographical order. While both methods aim to generate all possible combinations of `k` numbers out of `n`, the iterative approach has been found to be faster for the given test cases. \n\n1. **Backtracking Approach**: This approach involves a recursive function, `backtrack`, that generates all combinations of `k` numbers. We iterate over all numbers from `first` to `n`. For each number `i`, we add it to the current combination and then recursively generate all the combinations of the next numbers. After that, we remove `i` from the current combination to backtrack and try the next number.\n\n2. **Iterative Approach**: This approach uses an iterative algorithm to generate combinations. It maintains a list of current indices and generates the next combination from the current one by incrementing the rightmost element that hasn\'t reached its maximum value yet.\n\n# Approach - Backtracking\n\nOur approach specifically involves a recursive function, `backtrack`, that generates all combinations of \\(k\\) numbers. Here\'s a step-by-step walkthrough of the process:\n\n1. **Initialization**: We define an empty list, `output`, to store all our valid combinations. We also initialize our `backtrack` function, which takes as input parameters the first number to add to the current combination (`first`) and the current combination itself (`curr`).\n\n2. **Base case for recursion**: Within the `backtrack` function, we first check if the length of the current combination (`curr`) is equal to \\(k\\). If it is, we have a valid combination and add a copy of it to our `output` list.\n\n3. **Loop through the numbers**: For each number \\(i\\) in the range from `first` to \\(n\\), we add \\(i\\) to the current combination (`curr`).\n\n4. **Recursive call**: We then make a recursive call to `backtrack`, incrementing the value of `first` by 1 for the next iteration and passing the current combination as parameters. This step allows us to generate all combinations of the remaining numbers.\n\n5. **Backtrack**: After exploring all combinations with \\(i\\) included, we need to remove \\(i\\) from the current combination. This allows us to backtrack and explore the combinations involving the next number. This is done using the `pop()` method, which removes the last element from the list.\n\n6. **Return the result**: Finally, after all recursive calls and backtracking, the `backtrack` function will have filled our `output` list with all valid combinations of \\(k\\) numbers. We return this list as our final result.\n\n# Approach - Iterative\n\nThe approach taken to solve this problem involves the use of function calls to generate all possible combinations. Here is a more detailed step-by-step breakdown of the approach:\n\n1. **Define the `generate_combinations` function:** This function takes in two parameters: `elems` (the range of numbers to choose from) and `num` (the number of elements in each combination). It begins by converting `elems` to a tuple (`elems_tuple`) for efficient indexing. It then checks if `num` is greater than the total number of elements; if it is, the function returns as it\'s impossible to select more elements than exist in the range.\n\n2. **Initialize indices:** An array `curr_indices` is initialized with the first `num` indices. This will represent the indices in `elems_tuple` that we are currently considering for our combination.\n\n3. **Generate combinations:** The function enters a loop. In each iteration, it first generates a combination by picking elements from `elems_tuple` using the indices in `curr_indices` and yields it. This is done using a tuple comprehension.\n\n4. **Update indices:** Next, the function attempts to update `curr_indices` to represent the next combination. It starts from the end of `curr_indices` and moves towards the start, looking for an index that hasn\'t reached its maximum value (which is its position from the end of `elems_tuple`). When it finds such an index, it increments it and sets all subsequent indices to be one greater than their previous index. This ensures that we generate combinations in increasing order. If it doesn\'t find any index to increment (meaning we have generated all combinations), it breaks out of the loop and the function returns.\n\n5. **Call the `generate_combinations` function:** In the `combine` method, the `generate_combinations` function is called with the range `[1, n+1]` and `k` as arguments. The returned combinations are tuples, so a list comprehension is used to convert each combination into a list.\n\n# Complexity - Iterative\n\n- **Time complexity:** The time complexity is \\(O(C(n, k))\\), where \\(n\\) is the total number of elements and \\(k\\) is the number of elements in each combination. This is because the function generates each combination once. Here, \\(C(n, k)\\) denotes the number of ways to choose \\(k\\) elements from \\(n\\) elements without regard to the order of selection, also known as "n choose k".\n\n- **Space complexity:** The space complexity is also \\(O(C(n, k))\\) as we store all combinations in a list. \n\n\n# Complexity - Backtracking\n- **Time complexity:** The time complexity of this approach is (O(C(n, k)*k)). This is because in the worst-case scenario, we would need to explore all combinations of \\(k\\) out of \\(n\\) (which is C(n, k) and for each combination, it takes \\(O(k)\\) time to make a copy of it.\n- **Space complexity:** The space complexity is \\(O(k)\\). This is because, in the worst case, if we consider the function call stack size in a depth-first search traversal, we could end up going as deep as \\(k\\) levels.\n\n# Code - Iterative\n```Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def generate_combinations(elems, num):\n elems_tuple = tuple(elems)\n total = len(elems_tuple)\n if num > total:\n return\n curr_indices = list(range(num))\n while True:\n yield tuple(elems_tuple[i] for i in curr_indices)\n for idx in reversed(range(num)):\n if curr_indices[idx] != idx + total - num:\n break\n else:\n return\n curr_indices[idx] += 1\n for j in range(idx+1, num):\n curr_indices[j] = curr_indices[j-1] + 1\n\n return [list(combination) for combination in generate_combinations(range(1, n+1), k)]\n```\n``` Java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n generateCombinations(1, n, k, new ArrayList<Integer>(), result);\n return result;\n }\n\n private void generateCombinations(int start, int n, int k, List<Integer> combination, List<List<Integer>> result) {\n if (k == 0) {\n result.add(new ArrayList<>(combination));\n return;\n }\n for (int i = start; i <= n - k + 1; i++) {\n combination.add(i);\n generateCombinations(i + 1, n, k - 1, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination(k);\n generateCombinations(1, n, k, combination, result);\n return result;\n }\n\nprivate:\n void generateCombinations(int start, int n, int k, vector<int> &combination, vector<vector<int>> &result) {\n if (k == 0) {\n result.push_back(combination);\n return;\n }\n for (int i = start; i <= n; ++i) {\n combination[combination.size() - k] = i;\n generateCombinations(i + 1, n, k - 1, combination, result);\n }\n }\n};\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Combine(int n, int k) {\n var result = new List<IList<int>>();\n GenerateCombinations(1, n, k, new List<int>(), result);\n return result;\n }\n \n private void GenerateCombinations(int start, int n, int k, List<int> combination, IList<IList<int>> result) {\n if (k == 0) {\n result.Add(new List<int>(combination));\n return;\n }\n for (var i = start; i <= n; ++i) {\n combination.Add(i);\n GenerateCombinations(i + 1, n, k - 1, combination, result);\n combination.RemoveAt(combination.Count - 1);\n }\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function(n, k) {\n const result = [];\n generateCombinations(1, n, k, [], result);\n return result;\n};\n\nfunction generateCombinations(start, n, k, combination, result) {\n if (k === 0) {\n result.push([...combination]);\n return;\n }\n for (let i = start; i <= n; ++i) {\n combination.push(i);\n generateCombinations(i + 1, n, k - 1, combination, result);\n combination.pop();\n }\n}\n```\n\n# Code - Backtracking\n``` Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def backtrack(first = 1, curr = []):\n if len(curr) == k:\n output.append(curr[:])\n return\n for i in range(first, n + 1):\n curr.append(i)\n backtrack(i + 1, curr)\n curr.pop()\n output = []\n backtrack()\n return output\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination;\n backtrack(n, k, 1, combination, result);\n return result;\n }\n\nprivate:\n void backtrack(int n, int k, int start, vector<int>& combination, vector<vector<int>>& result) {\n if (combination.size() == k) {\n result.push_back(combination);\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.push_back(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop_back();\n }\n }\n};\n```\n``` Java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n backtrack(n, k, 1, new ArrayList<>(), result);\n return result;\n }\n\n private void backtrack(int n, int k, int start, List<Integer> combination, List<List<Integer>> result) {\n if (combination.size() == k) {\n result.add(new ArrayList<>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.add(i);\n backtrack(n, k, i + 1, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n``` JavaScript []\nvar combine = function(n, k) {\n const result = [];\n backtrack(n, k, 1, [], result);\n return result;\n};\n\nfunction backtrack(n, k, start, combination, result) {\n if (combination.length === k) {\n result.push([...combination]);\n return;\n }\n for (let i = start; i <= n; i++) {\n combination.push(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop();\n }\n}\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Combine(int n, int k) {\n IList<IList<int>> result = new List<IList<int>>();\n Backtrack(n, k, 1, new List<int>(), result);\n return result;\n }\n\n private void Backtrack(int n, int k, int start, IList<int> combination, IList<IList<int>> result) {\n if (combination.Count == k) {\n result.Add(new List<int>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.Add(i);\n Backtrack(n, k, i + 1, combination, result);\n combination.RemoveAt(combination.Count - 1);\n }\n }\n}\n```\n\n## Performances - Iterative\n| Language | Runtime | Rank | Memory |\n|----------|---------|------|--------|\n| Java | 1 ms | 100% | 45.3 MB|\n| C++ | 14 ms | 90.1%| 9.2 MB |\n| Python3 | 68 ms | 99.72%| 18.8 MB|\n| JavaScript | 79 ms | 99.84%| 48.6 MB|\n| C# | 101 ms | 93.1%| 44.1 MB|\n\n## Performances - Backtracking\n| Language | Runtime | Beats | Memory |\n|----------|---------|-------|--------|\n| Java | 17 ms | 75.30%| 44.5 MB|\n| C++ | 21 ms | 85.40%| 9.1 MB |\n| JavaScript | 86 ms | 97.78%| 48 MB |\n| C# | 105 ms | 88.60%| 44.4 MB|\n| Python3 | 286 ms | 78.68%| 18.2 MB|\n\nI hope you found this solution helpful! If so, please consider giving it an upvote. If you have any questions or suggestions for improving the solution, don\'t hesitate to leave a comment. Your feedback not only helps me improve my answers, but it also helps other users who might be facing similar problems. Thank you for your support!\n
110
1
['C++', 'Java', 'Python3', 'JavaScript', 'C#']
8
combinations
Python easy to understand DFS solution
python-easy-to-understand-dfs-solution-b-8m90
\nclass Solution(object):\n def combine(self, n, k):\n ret = []\n self.dfs(list(range(1, n+1)), k, [], ret)\n return ret\n \n def
oldcodingfarmer
NORMAL
2015-07-18T13:37:37+00:00
2020-09-10T14:40:35.377731+00:00
20,492
false
```\nclass Solution(object):\n def combine(self, n, k):\n ret = []\n self.dfs(list(range(1, n+1)), k, [], ret)\n return ret\n \n def dfs(self, nums, k, path, ret):\n if len(path) == k:\n ret.append(path)\n return \n for i in range(len(nums)):\n self.dfs(nums[i+1:], k, path+[nums[i]], ret)\n```
107
3
['Backtracking', 'Python']
14
combinations
My shortest c++ solution,using dfs
my-shortest-c-solutionusing-dfs-by-nanga-7dud
my idea is using backtracking ,every time I push a number into vector,then I push a bigger one into it;\nthen i pop the latest one,and push a another bigger on
nangao
NORMAL
2014-10-10T05:48:27+00:00
2018-10-08T20:47:58.421472+00:00
24,619
false
my idea is using backtracking ,every time I push a number into vector,then I push a bigger one into it;\nthen i pop the latest one,and push a another bigger one...\nand if I has push k number into vector,I push this into result;\n\n**this solution take 24 ms.**\n\n\n\n class Solution {\n public:\n vector<vector<int> > combine(int n, int k) {\n vector<vector<int> >res;\n if(n<k)return res;\n vector<int> temp(0,k);\n combine(res,temp,0,0,n,k);\n return res;\n }\n \n void combine(vector<vector<int> > &res,vector<int> &temp,int start,int num,int n ,int k){\n if(num==k){\n res.push_back(temp);\n return;\n }\n for(int i = start;i<n;i++){\n temp.push_back(i+1);\n combine(res,temp,i+1,num+1,n,k);\n temp.pop_back();\n }\n }\n };
99
2
['Depth-First Search']
16
combinations
General Backtracking questions solutions in Python for reference :
general-backtracking-questions-solutions-0mur
I have taken solutions of @caikehe from frequently asked backtracking questions which I found really helpful and had copied for my reference. I thought this pos
coders-block
NORMAL
2019-11-15T06:08:58.797774+00:00
2019-11-15T06:30:47.768802+00:00
6,863
false
I have taken solutions of @caikehe from frequently asked backtracking questions which I found really helpful and had copied for my reference. I thought this post will be helpful for everybody as in an interview I think these basic solutions can come in handy. Please add any more questions in comments that you think might be important and I can add it in the post.\n\n#### Combinations :\n```\ndef combine(self, n, k):\n res = []\n self.dfs(xrange(1,n+1), k, 0, [], res)\n return res\n \ndef dfs(self, nums, k, index, path, res):\n #if k < 0: #backtracking\n #return \n if k == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(nums)):\n self.dfs(nums, k-1, i+1, path+[nums[i]], res)\n``` \n\t\n#### Permutations I\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n res = []\n self.dfs(nums, [], res)\n return res\n\n def dfs(self, nums, path, res):\n if not nums:\n res.append(path)\n #return # backtracking\n for i in range(len(nums)):\n self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)\n``` \n\n#### Permutations II\n```\ndef permuteUnique(self, nums):\n res, visited = [], [False]*len(nums)\n nums.sort()\n self.dfs(nums, visited, [], res)\n return res\n \ndef dfs(self, nums, visited, path, res):\n if len(nums) == len(path):\n res.append(path)\n return \n for i in xrange(len(nums)):\n if not visited[i]: \n if i>0 and not visited[i-1] and nums[i] == nums[i-1]: # here should pay attention\n continue\n visited[i] = True\n self.dfs(nums, visited, path+[nums[i]], res)\n visited[i] = False\n```\n\n \n#### Subsets 1\n\n\n```\ndef subsets1(self, nums):\n res = []\n self.dfs(sorted(nums), 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Subsets II \n\n\n```\ndef subsetsWithDup(self, nums):\n res = []\n nums.sort()\n self.dfs(nums, 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n if i > index and nums[i] == nums[i-1]:\n continue\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Combination Sum \n\n\n```\ndef combinationSum(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, nums, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return \n for i in xrange(index, len(nums)):\n self.dfs(nums, target-nums[i], i, path+[nums[i]], res)\n```\n\n \n \n#### Combination Sum II \n\n```\ndef combinationSum2(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, candidates, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(candidates)):\n if i > index and candidates[i] == candidates[i-1]:\n continue\n self.dfs(candidates, target-candidates[i], i+1, path+[candidates[i]], res)\n```
70
1
['Backtracking', 'Python', 'Python3']
4
combinations
✅☑️ Best C++ Solution Ever || Easy Solution || Backtracking || One Stop Solution.
best-c-solution-ever-easy-solution-backt-yqfp
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can solve this problem using Array + Backtracking.\n\n# Approach\n Describe your app
its_vishal_7575
NORMAL
2023-02-21T11:40:02.150041+00:00
2023-02-21T11:40:02.150090+00:00
7,298
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using Array + Backtracking.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the approach by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity : O(k*nCk), here nCk means the binomial coefficient of picking k elements out of n elements. where nCk = C(n,k) = n!/(n\u2212k)!\xD7k!.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity : O(nCk), as stated above the nCk here refers to the binomial coefficient.\n\n# Code\n```\n/*\n\n Time Complexity : O(k*nCk), here nCk means the binomial coefficient of picking k elements out of n elements.\n where nCk = C(n,k) = n!/(n\u2212k)!\xD7k!.\n\n Space Complexity : O(nCk), as stated above the nCk here refers to the binomial coefficient.\n\n Solved using Array + Backtracking.\n\n*/\n\nclass Solution { \nprivate: \n void combine(int n, int k, vector<vector<int>> &output, vector<int> &temp, int start){\n if(temp.size() == k){\n output.push_back(temp);\n return;\n }\n for(int i=start; i<=n; i++){\n temp.push_back(i);\n combine(n, k, output, temp, i+1);\n temp.pop_back();\n }\n } \npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> output;\n vector<int> temp;\n combine(n, k, output, temp, 1);\n return output;\n }\n};\n\n```\n\n**IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.**\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg](https://assets.leetcode.com/users/images/0a95fea4-64f4-4502-82aa-41db6d77c05c_1676054939.8270252.jpeg)
61
1
['Array', 'Backtracking', 'C++']
3
combinations
AC Python backtracking iterative solution 60 ms
ac-python-backtracking-iterative-solutio-nedo
def combine(self, n, k):\n ans = []\n stack = []\n x = 1\n while True:\n l = len(stack)\n if l == k:\n
dietpepsi
NORMAL
2015-10-01T22:04:08+00:00
2018-10-04T03:03:19.081884+00:00
19,310
false
def combine(self, n, k):\n ans = []\n stack = []\n x = 1\n while True:\n l = len(stack)\n if l == k:\n ans.append(stack[:])\n if l == k or x > n - k + l + 1:\n if not stack:\n return ans\n x = stack.pop() + 1\n else:\n stack.append(x)\n x += 1\n\n # 26 / 26 test cases passed.\n # Status: Accepted\n # Runtime: 60 ms\n # 98.51%\n\n\nCombinations is typical application for backtracking. Two conditions for back track: (1) the stack length is already k (2) the current value is too large for the rest slots to fit in since we are using ascending order to make sure the uniqueness of each combination.
61
1
[]
27
combinations
2 Methods || Backtracking && Recursion || Video || C++ || Java || Python
2-methods-backtracking-recursion-video-c-vcr5
Intuition\n Describe your first thoughts on how to solve this problem. \nfind recursively by take not take.\n\nFor detailed explanation you can refer to my yout
shivam-727
NORMAL
2023-08-01T00:21:01.544453+00:00
2023-08-16T11:14:22.620128+00:00
15,292
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfind recursively by take not take.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\nhttps://youtu.be/QHaj0oRoYCI\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\nBoth the methods i discussed in depth\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwhich is more efficient and why ?\n\nBoth `solve1` and `solve2` are recursive methods used to find combinations of `k` elements from the range `[1, n]`. However, they use different approaches to achieve the same result. Let\'s compare their efficiency:\n\n1. `solve1`:\n - Approach: This method uses a binary tree-like recursion structure where, at each step, it either includes the current `num` in the combination or skips it.\n - Complexity: The time complexity of `solve1` is O(2^n) because for each number `num`, there are two recursive calls (one with `num` included and the other with `num` skipped), and this branching continues until `num` reaches `tot+1`.\n\n2. `solve2`:\n - Approach: This method uses a more straightforward approach with a loop that starts from the current `num` and iterates up to `tot`. At each iteration, it includes the current number in the combination and recursively explores the next elements.\n - Complexity: The time complexity of `solve2` is also O(2^n), but it performs better than `solve1` in practice due to the way the recursion is structured. It avoids some redundant recursive calls that are present in `solve1`.\n\nOverall, both methods have the same time complexity, and neither one is inherently more efficient than the other. The key difference is in the way the recursion is structured. `solve1` explores all possible combinations using a binary tree-like structure, while `solve2` explores combinations using a loop.\n\nIn practice, `solve2` is likely to perform better than `solve1` due to the reduced overhead from not making redundant recursive calls. However, the exact performance difference between the two methods can vary based on the specific inputs and other factors like the compiler optimizations.\n\nIn this case, the `combine` method uses `solve2` to find the combinations, which is a reasonable choice for efficiency and readability. The `solve2` method has a more straightforward implementation and avoids unnecessary recursive calls, making it generally more efficient than `solve1`.\n\n# Complexity\n- Time complexity:$$O(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: at most $$O(2^n)$$ if k = n \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>>res;\n void solve1(int num,int tot,int k,vector<int>&ans){\n if(num==tot+1){\n //filter the size of subsequence of size k.\n if(ans.size()==k)\n res.push_back(ans);\n return;\n }\n\n ans.push_back(num);\n solve1(num+1,tot,k,ans);//take current number\n ans.pop_back();\n solve1(num+1,tot,k,ans);//not take current number\n }\n void solve2(int num,int tot,int k,vector<int>&ans){\n if(ans.size()==k){\n res.push_back(ans);\n return;\n }\n for(int i=num;i<=tot;i++){\n ans.push_back(i);\n solve2(i+1,tot,k,ans);//generating answer in sorted order\n// 1 12 123 13 like this\n ans.pop_back();\n }\n \n }\n vector<vector<int>> combine(int n, int k) {\n vector<int>ans;\n solve2(1,n,k,ans);\n return res;\n }\n};\n```\n```java []\nimport java.util.*;\n\npublic class Solution {\n List<List<Integer>> res = new ArrayList<>();\n\n void solve1(int num, int tot, int k, List<Integer> ans) {\n if (num == tot + 1) {\n if (ans.size() == k) {\n res.add(new ArrayList<>(ans));\n }\n return;\n }\n\n ans.add(num);\n solve1(num + 1, tot, k, ans);\n ans.remove(ans.size() - 1);\n solve1(num + 1, tot, k, ans);\n }\n\n void solve2(int num, int tot, int k, List<Integer> ans) {\n if (ans.size() == k) {\n res.add(new ArrayList<>(ans));\n return;\n }\n for (int i = num; i <= tot; i++) {\n ans.add(i);\n solve2(i + 1, tot, k, ans);\n ans.remove(ans.size() - 1);\n }\n }\n\n public List<List<Integer>> combine(int n, int k) {\n List<Integer> ans = new ArrayList<>();\n solve2(1, n, k, ans);\n return res;\n }\n}\n\n```\n```python []\nclass Solution:\n def __init__(self):\n self.res = []\n\n def solve1(self, num, tot, k, ans):\n if num == tot + 1:\n if len(ans) == k:\n self.res.append(ans[:])\n return\n\n ans.append(num)\n self.solve1(num + 1, tot, k, ans)\n ans.pop()\n self.solve1(num + 1, tot, k, ans)\n\n def solve2(self, num, tot, k, ans):\n if len(ans) == k:\n self.res.append(ans[:])\n return\n for i in range(num, tot + 1):\n ans.append(i)\n self.solve2(i + 1, tot, k, ans)\n ans.pop()\n\n def combine(self, n, k):\n ans = []\n self.solve2(1, n, k, ans)\n return self.res\n\n```\n# Make sure to upvote if you understood the solution.
52
3
['Backtracking', 'Recursion', 'Python', 'C++', 'Java']
6
combinations
[Python] 2 solutions - Bitmasking, Backtracking - Clean & Concise
python-2-solutions-bitmasking-backtracki-r5pf
\u2714\uFE0F Solution 1: Bitmasking\npython\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n \n def countBit1s(num, n
hiepit
NORMAL
2021-09-11T02:47:35.178671+00:00
2024-04-12T21:47:20.480032+00:00
2,105
false
**\u2714\uFE0F Solution 1: Bitmasking**\n```python\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n \n def countBit1s(num, n):\n bits = 0\n for i in range(n):\n if (num >> i) & 1:\n bits += 1\n return bits\n \n ans = []\n for mask in range(1 << n):\n if countBit1s(mask, n) != k: continue\n sub = []\n for i in range(n):\n if (mask >> i) & 1:\n sub.append(i+1)\n ans.append(sub)\n return ans\n```\nComplexity:\n- Time: `O(2^n * n)`, where `n <= 20`\n- Space: `O(C(n, k))`, where `k <= n`\n\n---\n**\u2714\uFE0F Solution 2: Backtracking (Version 1)**\n```python\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n ans = []\n\n def bt(i, path):\n if len(path) == k:\n ans.append(path[::])\n return\n if i == n: return\n\n # No pick\n bt(i + 1, path)\n\n # Pick\n path.append(i + 1)\n bt(i + 1, path)\n path.pop()\n\n bt(0, [])\n return ans\n```\nComplexity:\n- Time: `O(C(n, k) * k)`, where `n <= 20`\n- Space: `O(C(n, k))`, where `k <= n`\n\n---\n**\u2714\uFE0F Solution 3: Backtracking (Version 2)**\n```python\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n ans = []\n\n def bt(i, path):\n if len(path) == k:\n ans.append(path[::])\n return\n\n for j in range(i, n):\n path.append(j+1)\n bt(j+1, path)\n path.pop()\n\n bt(0, [])\n return ans\n```\nComplexity:\n- Time: `O(C(n, k) * k)`, where `n <= 20`\n- Space: `O(C(n, k))`, where `k <= n`
41
0
['Backtracking', 'Bitmask']
2
combinations
Fast & simple python code . recursive
fast-simple-python-code-recursive-by-bol-8nns
def combine(self, n, k):\n if k==1:\n return [[i] for i in range(1,n+1)]\n elif k==n:\n return [[i for i in range(1,n+1)]]\n
boler1132
NORMAL
2015-05-20T14:44:47+00:00
2015-05-20T14:44:47+00:00
6,116
false
def combine(self, n, k):\n if k==1:\n return [[i] for i in range(1,n+1)]\n elif k==n:\n return [[i for i in range(1,n+1)]]\n else:\n rs=[]\n rs+=self.combine(n-1,k)\n part=self.combine(n-1,k-1)\n for ls in part:\n ls.append(n)\n rs+=part\n return rs
35
1
[]
1
combinations
Two Approach, Recursive & Iterative, [C++]
two-approach-recursive-iterative-c-by-ak-qwhq
Implementation\n\n\n1st Approach\nRecursive Solution, Backtracking\n\nclass Solution {\npublic:\n void findCombination(vector<vector<int>> &res, vector<int>
akashsahuji
NORMAL
2021-11-19T07:13:45.334867+00:00
2021-11-19T07:13:45.334912+00:00
2,913
false
Implementation\n\n\n**1st Approach\nRecursive Solution, Backtracking**\n```\nclass Solution {\npublic:\n void findCombination(vector<vector<int>> &res, vector<int> temp, int index, int n, int k){\n if(temp.size() == k){\n res.push_back(temp);\n return;\n }\n for(int itr = index; itr < n; itr++){\n temp.push_back(itr+1);\n findCombination(res, temp, itr+1, n, k);\n temp.pop_back();\n }\n }\n \n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> res;\n findCombination(res, vector<int>(), 0, n, k);\n return res;\n }\n};\n```\n\n\n**2nd Approach\nIterative Solution**\n```\nclass Solution {\npublic: \n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> res;\n vector<int> temp(k, 0);\n int itr = 0;\n while(itr > -1){\n temp[itr]++;\n if(temp[itr] > n) itr--;\n else if(itr == k-1) res.push_back(temp);\n else{ \n itr++;\n temp[itr] = temp[itr-1];\n }\n }\n return res;\n }\n};\n```\nIf you find any issue in understanding the solution then comment below, will try to help you.\nIf you found my solution useful.\nSo **please do upvote and encourage me** to document all leetcode problems\uD83D\uDE03\nHappy Coding **:)**
30
0
['Backtracking', 'Depth-First Search', 'Recursion', 'C', 'Combinatorics', 'Iterator']
6
combinations
DP for the problem
dp-for-the-problem-by-left_peter-1js1
I didn't see any DP solution for this problem, so I share mine:\nThe idea is simple, if the combination k out of n (select k elements from [1,n]) is combine(k,
left_peter
NORMAL
2014-10-10T02:45:44+00:00
2014-10-10T02:45:44+00:00
9,422
false
I didn't see any DP solution for this problem, so I share mine:\nThe idea is simple, if the combination k out of n (select k elements from [1,n]) is combine(k, n).\n\nLet's consider how can we get combine(k, n) by adding the last element n to something we already have (combine(k - 1, n - 1) and combine(k, n - 1)). Actually, the combine(k, n) has two parts, one part is all combinations without n, it's combine(k, n - 1), another is all combinations with n, which can be gotten by appending n to every element in combine(k - 1, n - 1). Note, the combine(i, i) is what we can get directly.\n\nBelow is my code:\n\n\n public class Solution\n {\n // Combine(n, n).\n private List<Integer> allContain(int n)\n {\n final List<Integer> result = new ArrayList<>();\n for (int i = 1; i <= n; ++i)\n {\n result.add(i);\n }\n \n return result;\n }\n \n public List<List<Integer>> combine(int n, int k)\n {\n List<List<List<Integer>>> previous = new ArrayList<>();\n \n for (int i = 0; i <= n; ++i)\n {\n previous.add(Collections.singletonList(Collections.<Integer>emptyList()));\n }\n \n for (int i = 1; i <= k; ++i)\n {\n final List<List<List<Integer>>> current = new ArrayList<>();\n current.add(Collections.singletonList(allContain(i)));\n \n // Combine(i, j).\n for (int j = i + 1; j <= n; ++j)\n {\n final List<List<Integer>> list = new ArrayList<>();\n \n // Combine(i, j - 1).\n list.addAll(current.get(current.size() - 1));\n \n // Comine(i - 1, j - 1).\n for (final List<Integer> item : previous.get(current.size()))\n {\n final List<Integer> newItem = new ArrayList<>(item);\n newItem.add(j);\n list.add(newItem);\n }\n \n current.add(list);\n }\n \n previous = current;\n }\n \n return (previous.size() == 0) ? Collections.<List<Integer>>emptyList() : previous.get(previous.size() - 1);\n }\n }
28
0
[]
4
combinations
Python/JS/Go by DFS + backtracking [w/ Hint] 有中文解說影片
pythonjsgo-by-dfs-backtracking-w-hint-yo-i8fp
\u4E2D\u6587\u8A73\u89E3 \u89E3\u8AAA\u5F71\u7247\nTutorial video in Chinese\n\nHint & recall:\n\nDFS template with backtracking\n\n\ndef dfs( parameter ):\n\n\
brianchiang_tw
NORMAL
2020-08-16T03:26:17.783883+00:00
2024-02-15T15:26:53.323529+00:00
4,485
false
[\u4E2D\u6587\u8A73\u89E3 \u89E3\u8AAA\u5F71\u7247\nTutorial video in Chinese](https://www.youtube.com/watch?v=ITwWVCfLgug&t=468s )\n\nHint & recall:\n\n**DFS template** with **backtracking**\n\n```\ndef dfs( parameter ):\n\n\tif stop condtion or base case:\n\t\t# base case:\n\t\tupdate result\n\t return\n\t\n\telse:\n\t\t# general cases:\n\t\tfor all possible next moves:\n\t\t\n\t\t select one next move\n\t\t\tdfs( paramter with selected next move )\n\t\t\tundo the selection\n\t\n\t\treturn\n```\n\n---\n\n\n---\n\n**Implementation** by DFS + backtracking in Python\n\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n \n result = []\n \n def gen_comb(start, cur_comb):\n \n if k == len(cur_comb):\n # base case, also known as stop condition \n\t\t\t\t\n result.append( cur_comb[::] )\n return\n \n else:\n # general case:\n \n # solve in DFS\n for i in range(start, n+1):\n \n cur_comb.append( i )\n \n gen_comb(i+1, cur_comb)\n \n cur_comb.pop()\n \n return\n # ----------------------------------------------\n \n gen_comb( start=1, cur_comb=[] )\n return result\n```\n---\n\n, or equivalent BFS implementation\n\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n\n result = []\n\n # Stating making subset from empty set with index 1\n bfs_queue = deque( [ (1, []) ] ) \n\n\n # Launch BFS from empty set to enumerate all valid subsets\n while bfs_queue:\n\n idx, cur = bfs_queue.popleft()\n\n if len(cur) == k:\n # Add current subset into result\n result.append( cur )\n continue\n \n # Visit all valid numbers with look-forward strategy\n for elem in range(idx, n+1):\n\n bfs_queue.append( (elem+1, cur + [ elem ] ) )\n \n return result\n```\n\n---\n\n**Implementation** by DFS + backtracking in JS\n\n```\nvar combine = function(n, k) {\n \n function* comb(start, curComb ){\n \n if(curComb.length == k){\n yield curComb;\n return;\n }\n \n for(let i = start; i <= n ; i++){\n yield* comb(i+1, [...curComb, i] );\n }\n return\n }\n \n \n return [ ...comb(start=1, curComb=[]) ];\n};\n```\n\nor \n\n```\nvar combine = function(n, k) {\n \n result = []\n //-----------------------------------\n var comb = function(start, curComb ){\n \n // Base case:\n if(curComb.length == k){\n result.push( [...curComb] ) ;\n return;\n }\n \n // General cases:\n for(let i = start; i <= n ; i++){\n curComb.push( i );\n comb(i+1, curComb );\n curComb.pop()\n }\n return\n }\n //-----------------------------------\n comb(start=1, curComb=[]);\n return result;\n};\n```\n\n---\n\n**Implementation** by DFS + backtracking in Go\n\n```\nfunc combine(n int, k int) [][]int {\n \n result := make([][]int, 0)\n \n //-------------------------------------------\n var comb func(start int, curComb []int)\n \n comb = func(start int, curComb []int){\n \n // Base case \n if len(curComb) == k{\n \n \n // make a copy of current combination\n dst := make([]int, k)\n copy(dst, curComb)\n result = append(result, dst)\n return\n } \n \n // General cases:\n for i := start ; i <= n ; i++{\n curComb = append(curComb, i)\n comb(i+1, curComb)\n curComb = curComb[:len(curComb)-1]\n }\n return\n }\n //-------------------------------------------\n comb(1, make([]int,0) )\n return result \n}\n```\n\n---\n\n**Implementation** by math formula for combination in Python\n\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n \n def comb(n, k):\n \n if n == 0 :\n return [ [] ]\n \n elif n == k:\n return [ [ i for i in range(1, n+1)] ]\n \n elif k == 1:\n return [ [i] for i in range(1,n+1) ]\n\n else:\n \n # By math formula: C(n, k) = C(n-1, k-1) + C(n-1, k)\n take_n = [ c + [n] for c in comb( n-1, k-1 ) ]\n not_to_take_n = [ c for c in comb( n-1, k ) ]\n\n return take_n + not_to_take_n\n \n # --------------------------------------\n \n return comb(n, k)\n```\n\n---\n\n
25
0
['Math', 'Backtracking', 'Depth-First Search', 'Breadth-First Search', 'Queue', 'Python', 'Go', 'Python3', 'JavaScript']
2
combinations
Iterative Java solution
iterative-java-solution-by-shpolsky-f2tm
Hi guys!\n\nThe idea is to iteratively generate combinations for all lengths from 1 to k. We start with a list of all numbers <= n as combinations for k == 1. W
shpolsky
NORMAL
2015-02-07T13:07:12+00:00
2018-09-13T17:54:37.745179+00:00
9,161
false
Hi guys!\n\nThe idea is to iteratively generate combinations for all lengths from 1 to k. We start with a list of all numbers <= n as combinations for k == 1. When we have all combinations of length k-1, we can get the new ones for a length k with trying to add to each one all elements that are <= n and greater than the last element of a current combination. \n\nI think the code here will be much more understandable than further attempts to explain. :) See below.\n\nHope it helps!\n\n----------\n\n public class Solution {\n public List<List<Integer>> combine(int n, int k) {\n if (k == 0 || n == 0 || k > n) return Collections.emptyList();\n List<List<Integer>> combs = new ArrayList<>();\n for (int i = 1; i <= n; i++) combs.add(Arrays.asList(i));\n for (int i = 2; i <= k; i++) {\n List<List<Integer>> newCombs = new ArrayList<>();\n for (int j = i; j <= n; j++) {\n for (List<Integer> comb : combs) {\n if (comb.get(comb.size()-1) < j) {\n List<Integer> newComb = new ArrayList<>(comb);\n newComb.add(j);\n newCombs.add(newComb);\n }\n }\n }\n combs = newCombs;\n }\n return combs;\n }\n }
25
0
['Java']
4
combinations
Straight - forward Approach || Easiest Explaination || Java Code
straight-forward-approach-easiest-explai-ulbw
Here we have used Backtracking (TAKE & DON\'T TAKE Concept) to achieve the Possible Combinations. \n\nLet us understand the Methdology -\n1. The recursive funct
itssme
NORMAL
2022-07-27T08:29:02.330098+00:00
2022-07-27T08:29:02.330141+00:00
1,719
false
Here we have used Backtracking ***(TAKE & DON\'T TAKE Concept)*** to achieve the Possible Combinations. \n\nLet us understand the Methdology -\n**1.** The recursive function must have a Base (End) condition, right? So in our case what will be the base condition?\n**2.** Inside the recursive function **(solveitforMe)**, we are checking if the size of the combinations arraylist is equal to the k (where k is the value, which should be the size of the inner list) or not. If yes, then we have to add the combinations list with the main result arraylist. Else repeat the recursive function.\n**3.** Below recursive function **(solveitforMe)** will execute till num is less than n+1,and save the combinations of size k inside our combinations arraylist. When we have saved that combinations arraylist inside our result arraylist, then we will backtrack using the line -`combinations.remove(combinations.size()-1);` It will remove the last added element and will make way for the nex new element.\n\n**As Mentioned in Below Image:-**\n\n![image](https://assets.leetcode.com/users/images/42e98acf-883c-446a-9503-ac2edd6a77f5_1658910246.3118813.jpeg)\n\n\n**Here the Code Part (In Java):-**\n\nclass Solution {\n\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>(); //used to store the result (all the possible combonations)\n List<Integer> combinations = new ArrayList<>(); //use to store the combinations or we can say that subset\n \n solveitforMe(1,n,k,combinations,result); //Actual recursive logic\n \n return result; \n }\n \n private void solveitforMe(int num, int n, int k, List<Integer> combinations, List<List<Integer>> result){\n \n if(num>n+1) //OUR BASE CONDITION...if num is greater than the given n+1 then return (No more recusrive calls)\n return;\n \n if(combinations.size() == k){ //ANOTHER BASE CONDITION... if temp list size i=is equals to the given k, then it means we one of our combinations\n // System.out.println(combinations);\n result.add(new ArrayList(combinations)); //Add that combination into the result list and return\n return;\n }\n \n combinations.add(num); //Add(TAKE) that number (we two choose TAKE & DON\'T TAKE)\n solveitforMe(num+1,n,k,combinations,result); //Do the recursive call further\n \n combinations.remove(combinations.size()-1); //DON\'T TAKE that number\n solveitforMe(num+1,n,k,combinations,result); // & Do the recursive call further\n \n }\n}\n\n***Note: Kindly Upvote this article, if you found it helpful. Thanks For Reading!!***
24
0
['Backtracking', 'Recursion', 'Java']
3
combinations
Python3 solution with detailed explanation
python3-solution-with-detailed-explanati-0zv6
Combination questions can be solved with dfs most of the time. I\'m following caikehe\'s approach. Also, if you want to fully understand this concept and backtr
peyman_np
NORMAL
2020-07-11T00:00:22.799896+00:00
2020-08-24T22:17:01.014863+00:00
4,047
false
Combination questions can be solved with `dfs` most of the time. I\'m following [caikehe](https://leetcode.com/problems/combinations/discuss/26990/Easy-to-understand-Python-solution-with-comments.)\'s approach. Also, if you want to fully understand this concept and [backtracking](https://www.***.org/backtracking-introduction/), try to finish [this](https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A) post and do all the examples. \n\n\nWe have an array `[1, 2, ..., n]`, if `k == 0`, meaning combination of zero numbers which is nothing (lines `#7, 8, 9`), right? Return `[[]]`. \n\n\n```\ndef combine(self, n, k):\n res = [] #1\n self.dfs(range(1,n+1), k, 0, [], res) #2\n return res #3\n \ndef dfs(self, nums, k, index, path, res): #4\n\tprint(\'index is:\', index)\n print(\'path is:\', path)\n if k == 0: #7\n res.append(path) #8\n return # backtracking #9 \n for i in range(index, len(nums)): #10\n self.dfs(nums, k-1, i+1, path+[nums[i]], res) #11\n```\nLines `#1, 2, 3` are the main function, where you initialize `res = []`. Also, you call the `dfs` function to find all the combinations, and finally, you return the `res`. The `dfs` function is the main part of the code. Lines `#7, 8` were explained before. `dfs`fuction goes into deeper levels until these two lines get activated. Keep reading. \n\nLet\'s do an example for the rest! I define levels as the number of times `dfs` gets called recursively before moving on in the `for` loop of line `#10`. \n\n---- Level 0 (input: `nums`, `k=2`, `index = 0`, `path = []`, `res = []`). \nThe idea of `dfs` is that it starts from first entry of `nums = [1, 2, ..., n]`. At first, `nums[0]` gets chosen in line `#10`, it calls the `dfs` again in line `#11` with updated inputs and goes basically one level deeper to choose the second number in the combination (note that his combination would look something like `[1, ...]`, right? `nums` doesn\'t change, but since we have already chosen one entry, variables get updated `k = k - 1`. Also, since we\'re already chosen entry `0`, `index` variable becomes `i = i +1` to go one step deeper. \n\n---- Level 1 (input: `nums`, `k=1`, `index = 1`, `path = [1]`, `res = []`).\nNow, in line `#10`, the `range` changes. It starts from `1` to `len(nums)`. It goes in and calls `dfs` one more time.\n\n\n--- Level 2 (input: `nums`, `k=0`, `index = 2`, `path = [1,2]]`, `res = []`).\nThis time it gets stuck in line `#7`, and appends `path` to `res`. Now, `res = [[1,2]]`. \n\nDoes this make sense? \n\nAll these level just return one combination, right? ( `res = [[1,2]]`). Remember going into deeper levels happened when we were in line `#10` and called `dfs` for the first time in line `#11`, and then for the second time in level 1, and we ended up in level 2 and got stuck in line `#7`. Now, we go back one step to level 1 and move on in line `#10`. This time, `i = 1` and `index = 2`. Again we go back to level 2 and return `path = [1,3]`. This will be appended to `res` to get to `res = [[1,2],[1,3]]`. Finally, we exhaust all indices in level 1. We end up with `res = [[1,2],[1,3],[1,4]]`. We go up one level, to level 0. Move on in line `#10`, this time, we\'ll get to `path = [[2,3],[2,4]]`, and will update `res = [[1,2],[1,3],[1,3],[2,3],[2,4]]`. We keep going to get the final combination, we\'re done. \n\n\nIf you want to fully understand how this works, try to print some variables at the start of your `dfs` function. I printed `index` and `path` and this is the outcome. \n\n```\nindex is: 0\npath is: []\nindex is: 1\npath is: [1]\nindex is: 2\npath is: [1, 2]\nindex is: 3\npath is: [1, 3]\nindex is: 4\npath is: [1, 4]\nindex is: 2\npath is: [2]\nindex is: 3\npath is: [2, 3]\nindex is: 4\npath is: [2, 4]\nindex is: 3\npath is: [3]\nindex is: 4\npath is: [3, 4]\nindex is: 4\npath is: [4]\n\nFinal output: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\n```\n\nAnother way of doing this without the `index` variable is:\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n res = []\n self.dfs(range(1,n+1), k, [], res)\n return res\n \n def dfs(self, nums, k, path, res):\n if k == 0:\n res.append(path)\n return res\n \n if len(nums) >= k:\n for i in range(len(nums)):\n self.dfs(nums[i+1:], k-1, path+[nums[i]], res)\n return\n```\n\nThat\'s it! \n\n=====================================================================\nFinal note: Please let me know if you found any typo/error/etc. I\'ll try to fix it. \n\n\n\n\n
24
0
['Depth-First Search', 'Python', 'Python3']
2
combinations
Backtracking | Easy to Understand | Faster | Simple | JavaScript Submission
backtracking-easy-to-understand-faster-s-e5hh
Please do upvote, it motivates me to write more such post\uD83D\uDE03\n\n\nvar combine = function(n, k) {\n let out = comb(k, n);\n // console.log(out);\n
mrmagician
NORMAL
2020-01-09T09:11:12.578891+00:00
2020-01-09T09:11:12.578939+00:00
2,787
false
**Please do upvote, it motivates me to write more such post\uD83D\uDE03**\n\n```\nvar combine = function(n, k) {\n let out = comb(k, n);\n // console.log(out);\n return out;\n};\n\n\nfunction comb(max, n, out=[], curr = [], index = 1){\n if(curr.length===max){\n out.push(curr);\n return [];\n }\n else{\n while(index<=n){\n comb(max, n, out, [...curr, index], ++index);\n }\n return out;\n }\n}\n```
23
6
['Backtracking', 'JavaScript']
0
combinations
✔️Python||C||C++🔥99%✅Backtrack with graph explained || Beginner-friendly ^_^
pythoncc99backtrack-with-graph-explained-1is6
Intuition\nThis is a backtracking problem.\nWe made a recursion function, and get all combinations by take or not take specific number.\n\n# Approach\n## variab
luluboy168
NORMAL
2023-08-01T07:58:35.182571+00:00
2023-08-01T08:00:55.874846+00:00
3,283
false
# Intuition\nThis is a backtracking problem.\nWe made a recursion function, and get all combinations by take or not take specific number.\n\n# Approach\n## variables\n`nums` is the current combination.\n`pos` is the current position in `nums`\n`cur` is the current number\n\nIn the function `backtrack`:\nIf `pos == k`, we know that we got one of the combination.\nIf `pos != k`, we can try every possible number to fit in the current position, then we call `backtrack` again.\n\n## Here is a graph for better understand\n![image.png](https://assets.leetcode.com/users/images/662b5a0c-06a4-4ab0-81cb-686d45083b22_1690876441.72758.png)\n\n\n# Code\n<iframe src="https://leetcode.com/playground/LchAVxik/shared" frameBorder="0" width="1500" height="800"></iframe>\n\n# Please UPVOTE if this helps you!!\n![image.png](https://assets.leetcode.com/users/images/4398d9d1-2d84-4491-a253-b008ab0aaae7_1690875002.0471663.png)\n![image.png](https://assets.leetcode.com/users/images/1c4d8242-7ccb-483b-8920-1b918c7488ea_1690875941.0002797.png)\n![image.png](https://assets.leetcode.com/users/images/355d3712-b3ce-4e07-a742-7698b41245cd_1690875966.649884.png)\n
19
2
['Backtracking', 'C', 'Python', 'C++', 'Python3']
4
combinations
C++ concise recursive solution C(n,k) ->C(n-1,k-1) / 8ms
c-concise-recursive-solution-cnk-cn-1k-1-lheb
class Solution {\n public:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> temp;\n
susandebug
NORMAL
2015-08-26T13:30:23+00:00
2015-08-26T13:30:23+00:00
5,061
false
class Solution {\n public:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> temp;\n combine(1,n,k,ans,temp); //call fuction to get combination of k numbers which range is 1-n\n return ans;\n }\n private:\n void combine(int begin,int n, int k, vector<vector<int>> &ans, vector<int>& temp){\n if(k==0){ \n ans.push_back(temp);\n return;\n } \n //condition : n-i+1 is the range, range must greater than k\n for(int i=begin;n-i+1>=k;i++){ // for the ith iteration, get the combination of i and k-1 numbers differ from i.\n temp.push_back(i); \n combine(i+1,n,k-1,ans,temp);// get the combination of k-1 numbers which range is(i+1,n) \n temp.pop_back();\n }\n }\n };
19
0
['Recursion']
5
combinations
C++ || Bits approach || Day 1
c-bits-approach-day-1-by-chiikuu-sy2n
Code\n\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>>ans;\n for(int i=0;i<(1<<n) ;i++){\n
CHIIKUU
NORMAL
2023-08-01T05:57:57.406633+00:00
2023-08-01T09:00:02.991071+00:00
1,125
false
# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>>ans;\n for(int i=0;i<(1<<n) ;i++){\n vector<int>v;\n int f = __builtin_popcountll(i);\n if(f!=k)continue;\n for(int j=0;j<n;j++){\n if((1<<j) & i){\n v.push_back(j+1);\n }\n }\n ans.push_back(v);\n }\n return ans;\n }\n};\n```\n![upvote (2).jpg](https://assets.leetcode.com/users/images/09b697bd-323a-4b95-bf73-f51a8a72546d_1690869475.4465623.jpeg)\n
18
1
['Bit Manipulation', 'Bitmask', 'C++']
1
combinations
✅Recursive and Iterative solution using C++ with explanations
recursive-and-iterative-solution-using-c-vzgc
If you\u2019re interested in coding you can join my Discord Server, link in the comment section. Also if you find any mistakes please let me know. Thank you!\u2
dhruba-datta
NORMAL
2022-04-11T13:18:40.443224+00:00
2022-04-11T13:18:40.443264+00:00
1,617
false
> **If you\u2019re interested in coding you can join my Discord Server, link in the comment section. Also if you find any mistakes please let me know. Thank you!\u2764\uFE0F**\n> \n\n---\n\n\n## Explanation:\n\n### Solution 01\n\n- Using ***Recursive & Backtracking.***\n- As we have to take elements from 1 to n, first we\u2019re passing 1 for the first time to our recursive function.\n- Base case will be when the temp size will be equal to k, we\u2019ll push to ans and return it.\n- Else we\u2019ll iterate with a loop till current number to n & make a recursive call for next numbers.\n- Also after the function comes back we\u2019ve to remove the element from temp and continue the loop.\n- **Time complexity:** O((nCk)*k), where nCk is all possible subsets and k to copy subsets into ans vector.\n- **Space complexity:** O((nCk)*k), to store all n C k subset in the ans vector of size k.\n\n### Solution 02\n\n- Using ***Iterative Approach.***\n- Here we have 3 test cases:\n 1. `if(temp[itr] > n)` Here, temp array at the itr position is exhausted. So there is no possible value that can be inserted at this position anymore. Since we started with the temp being filled with all zeros and incremented it step by step, we must have already passed all possible values for that index. In this case, we step back to one index and see if we can still increase the one element at the index behind.\n 2. `if(itr == k-1)` Here, we have reached the end of our possible combination. Each of our combinations has a max length of k, so it doesn\'t make sense to look at arrays that are larger than that. At this point, we can just add to our final result whichever value we\'ve found.\n 3. `else` we are in a scenario where both 1. and 2. are not satisfied. This means that our temp array at the itr position is NOT exhausted and we are NOT at the end of our array. In this case, we fix the value at itr and step one index ahead and start increasing the value at itr+1. We also copy the value of itr to itr+1 because to avoid duplications we make sure that our array always maintains the property that it is sorted in increasing order.\n\n---\n\n## Code:\n\n```cpp\n//Solution 01:\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<int> temp;\n vector<vector<int>> ans;\n \n help(1, temp, ans, n, k);\n return ans;\n }\n \n void help(int num, vector<int> &temp, vector<vector<int>> &ans, int n, int k){\n if(temp.size() == k){\n ans.push_back(temp);\n return;\n }\n \n for(int i=num; i<=n; i++){\n temp.push_back(i);\n help(i+1, temp, ans, n, k);\n temp.pop_back(); \n }\n }\n};\n\n//Solution 02:\nclass Solution {\npublic: \n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> res;\n vector<int> temp(k, 0);\n int itr = 0;\n\n while(itr > -1){\n temp[itr]++;\n if(temp[itr] > n) itr--;\n else if(itr == k-1) res.push_back(temp);\n else{ \n itr++;\n temp[itr] = temp[itr-1];\n }\n }\n return res;\n }\n};\n```\n\n---\n\n> **Please upvote this solution**\n>
18
0
['Backtracking', 'Recursion', 'C', 'C++']
1
combinations
[Python] [4 Approaches] Explained + Visualized
python-4-approaches-explained-visualized-cc54
-------------------------------------------------------\n[1] Sub-optimal Iterative: TLE : 23 / 27 test cases passed.\n------------------------------------------
Hieroglyphs
NORMAL
2021-08-17T13:39:54.454884+00:00
2021-08-17T21:15:55.052079+00:00
1,392
false
-------------------------------------------------------\n[1] Sub-optimal Iterative: TLE : 23 / 27 test cases passed.\n-------------------------------------------------------\n-------------------------------------------------------\n- Generate all nodes/permutations (n!)\n- Check if the same combo seen before by sorting\n- `O(n!) * O(n!)`\nSimialr to permutations : https://leetcode.com/problems/permutations/discuss/993970/Python-4-Approaches-%3A-Visuals-%2B-Time-Complexity-Analysis\n```\ndef combine(self, n: int, k: int) -> List[List[int]]:\n\tres = []\n\t# seen = set() # -- we cannot use sum becuz 2+3 = 1+4\n\tnums = list(range(1, n+1))\n\tstack = [([], nums[::-1])]\n\twhile stack:\n\t\tcombo, nums = stack.pop()\n\t\tif len(combo) == k: # or if nums = n - k\n\t\t\tif sorted(combo) not in res:\n\t\t\t\tres.append(combo)\n\n\t\tfor i in range(len(nums)):\n\t\t\tif len(combo) >= k:\n\t\t\t\tcontinue\n\t\t\tnewNums = nums[:i] + nums[i+1:]\n\t\t\tnewCombo = combo + [nums[i]]\n\t\t\tstack.append((newCombo, newNums))\n\treturn res\n```\n-------------------------------------------------------\n[2] Recursive - without backtracking\n-------------------------------------------------------\n-------------------------------------------------------\n- Runtime: 524 ms, faster than 40.75% of Python3\n- Time : O(n C k) - only generate/traverse combinations that are size k\n- Space: O(n C k)\n\n![image](https://assets.leetcode.com/users/images/98c118a8-e58d-4544-a86a-cf0d414fb484_1629207443.824713.jpeg)\n- To make sure we do not generate permutations (different arrangement of the same combination)\n\t- The difference between generating permutations and combinations is that when generating the children node for the latter:\n\t - Only generate nodes whose indecies are greater than the current idex\n![image](https://assets.leetcode.com/users/images/2eba5eb0-7167-40af-ba27-bd61d586eb2c_1629207454.9767716.jpeg)\n\n```\ndef combine(self, n: int, k: int) -> List[List[int]]:\n # -- helper\n def recurse(start, combo):\n\t if len(combo) == k:\n\t\t res.append(combo)\n\n\t else:\n\t\t for i in range(start, n+1): # - traverse horizontal - move to/generate sibling node\n\t\t\t newCombo = combo + [i]\n\t\t\t recurse(i+1, newCombo) # - traverse vertically - DFS\n\t\t return res\n\n # -- main\n res = []\n return recurse(1, [])\n```` \n-------------------------------------------------------\n[3] Recursive - with backtracking\n-------------------------------------------------------\n-------------------------------------------------------\n- Runtime: 460 ms, faster than 67.80% of Python3\n- Time : O(n C k) - only generate/traverse combinations that are size k\n- Space: O(n C k)\n```\ndef combine(self, n: int, k: int) -> List[List[int]]:\n\n\t# -- helper\n\tdef recurse(start, combo):\n\t\tif len(combo) == k:\n\t\t\tres.append(combo[::]) # take a copy of combo at leaf before you pop/backtrack\n\t\telse:\n\t\t\tfor i in range(start, n+1):\n\t\t\t\tcombo.append(i) # maintain one combo variable for entire space tree\n\t\t\t\trecurse(i+1, combo)\n\t\t\t\tcombo.pop() # - bactrack to move horiontally to sibling node\n\t\t\treturn res\n\t# main\n\tres = []\n\treturn recurse(1, [])\n```\n-------------------------------------------------------\n[4] iterative\n-------------------------------------------------------\n-------------------------------------------------------\n- 560 ms faster than 29%\n- Time : O(n C k) - only generate/traverse combinations that are size k\n- Space: O(n C k)\n\n```\ndef combine(self, n: int, k: int) -> List[List[int]]:\n\tres = []\n\tstack = [(1, [])]\n\twhile stack:\n\t\tstart, combo = stack.pop()\n\t\tif len(combo) == k:\n\t\t\tres.append(combo)\n\n\t\telse: # -- Limit the length of combo to k\n\t\t\tfor i in range(start, n+1):\n\t\t\t\tnewCombo = combo + [i]\n\t\t\t\tstack.append((i+1, newCombo)) # -- go deeper\n\treturn res\n```
17
0
['Depth-First Search', 'Recursion', 'Iterator', 'Python']
1
combinations
🚀⚡WITHOUT BACKTRACKING✅ || [C++/Java/Py3/JS]🍨 || EASY n CLEAN Explanation 💖✅ || BEATS💯⚡
without-backtracking-cjavapy3js-easy-n-c-nvw7
ApproachFunction: combine(n, k) Initialize result as an empty list to store all valid combinations. Create a curr list of size k (preallocated) to store the cur
Fawz-Haaroon
NORMAL
2025-02-08T18:17:01.953959+00:00
2025-02-10T12:48:55.292546+00:00
1,911
false
# Approach ### **Function: `combine(n, k)`** 1. Initialize `result` as an empty list to store all valid combinations. 2. Create a `curr` list of size `k` (preallocated) to store the current combination. 3. Call the recursive `dfs(start, depth, n, k, curr, result)` function with: - `start = 1` (begin with the first number) - `depth = 0` (track how many elements are selected) ### **Recursive Function: `dfs(start, depth, n, k, curr, result)`** 1. **Base Case:** - If `depth == k`, add a copy of `curr` to `result` and return. 2. **Loop through valid numbers with pruning:** - Iterate `i` from `start` to `n - (k - depth) + 1` (pruning unnecessary iterations). - Assign `curr[depth] = i` (modify in place, avoiding `push_back()`). - Recur with `dfs(i + 1, depth + 1, n, k, curr, result)`. 3. **Backtracking Not Required:** - Since `curr` is a fixed-size array, no need to undo changes (`pop_back()` not needed). # **Complexity Analysis** - **Time Complexity:** `O(C(n, k))`, as each valid combination is generated exactly once. - **Space Complexity:** `O(k)`, since only a single `curr` array is used without extra copies. # Code ```cpp [] class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> result; vector<int> curr(k); dfs(1, 0, n, k, curr, result); return result; } private: void dfs(int start, int depth, int n, int k, vector<int>& curr, vector<vector<int>>& result) { // If we filled all k elements, add to result if (depth == k) { result.push_back(curr); return; } // Pruning: Only iterate till (n - (k - depth) + 1) for (int i = start; i <= n - (k - depth) + 1; ++i) { curr[depth] = i; dfs(i + 1, depth + 1, n, k, curr, result); } } }; ``` ```python [] class Solution: def combine(self, n: int, k: int): result = [] curr = [0] * k self.dfs(1, 0, n, k, curr, result) return result def dfs(self, start, depth, n, k, curr, result): if depth == k: result.append(curr[:]) # Append a copy of the list return # Pruning: iterate until (n - (k - depth) + 1) for i in range(start, n - (k - depth) + 2): curr[depth] = i self.dfs(i + 1, depth + 1, n, k, curr, result) ``` ```java [] import java.util.*; class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> result = new ArrayList<>(); int[] curr = new int[k]; dfs(1, 0, n, k, curr, result); return result; } private void dfs(int start, int depth, int n, int k, int[] curr, List<List<Integer>> result) { if (depth == k) { List<Integer> combination = new ArrayList<>(); for (int num : curr) combination.add(num); result.add(combination); return; } // Pruning to avoid unnecessary iterations for (int i = start; i <= n - (k - depth) + 1; i++) { curr[depth] = i; dfs(i + 1, depth + 1, n, k, curr, result); } } } ``` ```javascript [] /** * @param {number} n * @param {number} k * @return {number[][]} */ var combine = function(n, k) { let result = []; let curr = new Array(k); dfs(1, 0, n, k, curr, result); return result; }; function dfs(start, depth, n, k, curr, result) { if (depth === k) { result.push([...curr]); // Copy array before pushing return; } // Pruning: Only iterate till (n - (k - depth) + 1) for (let i = start; i <= n - (k - depth) + 1; i++) { curr[depth] = i; dfs(i + 1, depth + 1, n, k, curr, result); } } ``` ``` ✨ AN UPVOTE WILL BE APPRECIATED ^_~ ✨ ```
16
2
['Python', 'C++', 'Java', 'Python3', 'JavaScript']
0
combinations
🔥 Easy Backtracking for Generating Combinations
easy-backtracking-for-generating-combina-ymoh
Intuition\nIn this problem, we\'re asked to generate all possible combinations of \nk numbers out of n. My initial instinct was to use a recursive strategy, par
phistellar
NORMAL
2023-08-01T01:48:33.832492+00:00
2023-08-01T02:24:33.805419+00:00
2,372
false
# Intuition\nIn this problem, we\'re asked to generate all possible combinations of \nk numbers out of n. My initial instinct was to use a recursive strategy, particularly the backtracking approach. Backtracking is a powerful method that systematically explores all potential combinations, distinguishing the ones that meet our specific criteria - here, those combinations that have a length of k.\n\nWhile the backtracking approach is typically more intuitive and easier to understand, it\'s worth noting that it may not always be the fastest. There are other methods, such as the iterative approach proposed by vanAmsen [Iterative](https://leetcode.com/problems/combinations/solutions/3845249/iterative-backtracking-video-100-efficient-combinatorial-generation/) in this LeetCode solution, which can be more efficient. However, for the purposes of this explanation, we\'ll focus on the backtracking approach due to its intuitive nature and general applicability to many combinatorial problems.\n\n# Approach\nThe problem requires us to construct all potential combinations of \\(k\\) numbers from a total pool of \\(n\\) numbers. To tackle this problem, we utilize the principle of backtracking.\n\nBacktracking is a strategic algorithmic approach for finding all (or a subset of) solutions to a computational problem, particularly those that involve satisfying certain constraints. It works by progressively constructing candidates for the solution and discards a candidate as soon as it becomes apparent that the candidate cannot be extended into a viable solution.\n\nIn the context of our problem, we use a recursive function, `backtrack`, which is responsible for generating all combinations of \\(k\\) numbers. Here\'s a detailed breakdown of the process:\n\n1. **Initialization**: We start by creating an empty list, `output`, where we\'ll store all the valid combinations. We also establish our `backtrack` function, which takes two input parameters: the first number to be added to the current combination (`first`), and the current combination itself (`curr`).\n\n2. **Base case for recursion**: Inside the `backtrack` function, we first check whether the length of the current combination (`curr`) equals \\(k\\). If it does, it means we have a valid combination, so we add a copy of it to our `output` list.\n\n3. **Number iteration**: We then iterate over every number \\(i\\) within the range from `first` to \\(n\\), adding \\(i\\) to the current combination (`curr`).\n\n4. **Recursive call**: Next, we make a recursive call to `backtrack`, incrementing the value of `first` by 1 for the subsequent iteration and passing the current combination as parameters. This allows us to generate all combinations of the remaining numbers.\n\n5. **Backtrack**: Once we\'ve explored all combinations that include \\(i\\), we need to remove \\(i\\) from the current combination. This is our \'backtracking\' step, which allows us to explore combinations that involve the next number. We achieve this by using the `pop()` method, which removes the last element from the list.\n\n6. **Result return**: Finally, after all recursive calls and backtracking are complete, our `backtrack` function will have populated our `output` list with all valid combinations of \\(k\\) numbers. This list is then returned as our final result.\n\n# Complexity\n- Time complexity: The time complexity of this approach is \\(O(\\binom{n}{k} \\cdot k)\\). This is because, in a worst-case scenario, we would need to explore all combinations of \\(k\\) out of \\(n\\) (which is \\(\\binom{n}{k}\\)) and for each combination, it takes \\(O(k)\\) time to copy it.\n- Space complexity: The space complexity is \\(O(k)\\). This is because, in the worst-case scenario, if we consider the function call stack size during a depth-first search traversal, we could potentially go as deep as \\(k\\) levels."\n\n# Complexity\n- Time complexity: The time complexity of this approach is (O(C(n, k)*k)). This is because in the worst-case scenario, we would need to explore all combinations of \\(k\\) out of \\(n\\) (which is C(n, k) and for each combination, it takes \\(O(k)\\) time to make a copy of it.\n- Space complexity: The space complexity is \\(O(k)\\). This is because, in the worst case, if we consider the function call stack size in a depth-first search traversal, we could end up going as deep as \\(k\\) levels.\n\n# Code\n``` Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def backtrack(first = 1, curr = []):\n if len(curr) == k:\n output.append(curr[:])\n return\n for i in range(first, n + 1):\n curr.append(i)\n backtrack(i + 1, curr)\n curr.pop()\n output = []\n backtrack()\n return output\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination;\n backtrack(n, k, 1, combination, result);\n return result;\n }\n\nprivate:\n void backtrack(int n, int k, int start, vector<int>& combination, vector<vector<int>>& result) {\n if (combination.size() == k) {\n result.push_back(combination);\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.push_back(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop_back();\n }\n }\n};\n```\n``` Java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n backtrack(n, k, 1, new ArrayList<>(), result);\n return result;\n }\n\n private void backtrack(int n, int k, int start, List<Integer> combination, List<List<Integer>> result) {\n if (combination.size() == k) {\n result.add(new ArrayList<>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.add(i);\n backtrack(n, k, i + 1, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n``` JavaScript []\nvar combine = function(n, k) {\n const result = [];\n backtrack(n, k, 1, [], result);\n return result;\n};\n\nfunction backtrack(n, k, start, combination, result) {\n if (combination.length === k) {\n result.push([...combination]);\n return;\n }\n for (let i = start; i <= n; i++) {\n combination.push(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop();\n }\n}\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Combine(int n, int k) {\n IList<IList<int>> result = new List<IList<int>>();\n Backtrack(n, k, 1, new List<int>(), result);\n return result;\n }\n\n private void Backtrack(int n, int k, int start, IList<int> combination, IList<IList<int>> result) {\n if (combination.Count == k) {\n result.Add(new List<int>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.Add(i);\n Backtrack(n, k, i + 1, combination, result);\n combination.RemoveAt(combination.Count - 1);\n }\n }\n}\n```
15
0
['C++', 'Java', 'Python3', 'JavaScript', 'C#']
1
combinations
Java | TC:O(K*C(N,K)) | SC:O(K) | Optimized Iterative & Backtracking solutions
java-tcokcnk-scok-optimized-iterative-ba-5dvo
Backtracking (Recursive Solution)\n\n\n/**\n * Backtracking (Recursive Solution)\n *\n * Time complexity = InternalNodes in the RecursionTree + K * LeafNode
NarutoBaryonMode
NORMAL
2021-10-30T21:45:59.149100+00:00
2021-10-30T21:47:57.528894+00:00
931
false
**Backtracking (Recursive Solution)**\n\n```\n/**\n * Backtracking (Recursive Solution)\n *\n * Time complexity = InternalNodes in the RecursionTree + K * LeafNodes in RecursionTree\n * = (C(N,0) + C(N,1) + ... + C(N,K-1)) + K * C(N,K)\n *\n * Space Complexity = O(K) -> Depth of Recursion tree + Size of TempList\n *\n * N, K -> Input numbers.\n */\nclass Solution1 {\n public List<List<Integer>> combine(int n, int k) {\n if (n <= 0 || k < 0) {\n throw new IllegalArgumentException("invalid input");\n }\n\n List<List<Integer>> result = new ArrayList<>();\n if (k == 0) {\n result.add(new ArrayList<>());\n return result;\n }\n\n combineHelper(n, k, new ArrayList<>(), result);\n return result;\n }\n\n private void combineHelper(int n, int k, List<Integer> temp, List<List<Integer>> result) {\n if (k == 0) {\n result.add(new ArrayList<>(temp));\n return;\n }\n for (int i = n; i >= 1; i--) {\n temp.add(i);\n combineHelper(i - 1, k - 1, temp, result);\n temp.remove(temp.size() - 1);\n }\n }\n}\n```\n\n---\n**Iterative Solution. This solution takes less time as compared to above recursive solution. In every iteration we are creating a valid combination. Thus, the total time taken is Total number of combinations * K**\n\n```java\n/**\n * Iterative Solution\n *\n * Here each combination is sorted. Thus it sets the first lowest possible value\n * in the last column. Then it starts filling all possible values in the\n * previous column and so-on.\n * For N = 5, K = 3:\n * 1, 2, 3(Here 3 is lowest possible value for the last (third) column).\n *\n * We also add a N+1 value in the end so that we do not go over N while generating the combinations.\n *\n * 1, 2, 3, 6 --> In next combination we will increment 3 to 4 as 1,2 are in correct place if 3 is in the third column\n * 1, 2, 4, 6 --> Now we can fill 2 & 3 in the column before 4.\n * 1, 3, 4, 6 --> Keep it sorted, we cannot increase 3 to 5. So we move on to first column and increment it to 2.\n * 2, 3, 4, 6 --> Now we have exhausted the possible combinations with 4 in the third column.\n * Now we will increase 4 to 5. And reset the first 2 columns\n * With 5 in the third column, second column can have 2, 3, 4\n * 1, 2, 5, 6 ->\n * 1, 3, 5, 6 -> First C column can take 1, 2\n * 2, 3, 5, 6 -> We cannot increment first column beyond 2 with 3 in second column. So we will increase second column to 4.\n * 1, 4, 5, 6 -> Now first column can have 1, 2, 3\n * 2, 4, 5, 6\n * 3, 4, 5, 6 -> Exhausted all possible combinations. Exit now.\n *\n * Time complexity = 2*K * Total number of possible combinations\n * = O(2 * K * C(N, K))\n *\n * Space Complexity = O(K+1) -> Size of TempList\n *\n * N, K -> Input numbers.\n */\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n if (n <= 0 || k < 0) {\n throw new IllegalArgumentException("invalid input");\n }\n\n List<List<Integer>> result = new ArrayList<>();\n if (k == 0) {\n result.add(new ArrayList<>());\n return result;\n }\n\n List<Integer> temp = new ArrayList<>(k + 1);\n for (int i = 1; i <= k; i++) {\n temp.add(i);\n }\n temp.add(n + 1);\n\n int i = 0;\n while (i < k) {\n result.add(new ArrayList<>(temp.subList(0, k)));\n i = 0;\n while (i < k && (temp.get(i) + 1 == temp.get(i + 1))) {\n temp.set(i, i + 1);\n i++;\n }\n temp.set(i, temp.get(i) + 1);\n }\n\n return result;\n }\n}\n```
15
0
['Backtracking', 'Iterator', 'Java']
2
combinations
Perhaps the simplest solution using recursion(backtracing).
perhaps-the-simplest-solution-using-recu-vz5h
The idea is that C(n,k) = C(n-1, k-1) U n + C(n-1,k), do you get this?\n\n class Solution {\n public:\n vector > combine(int n, int k) {\n
ever4kenny
NORMAL
2014-11-12T07:36:47+00:00
2014-11-12T07:36:47+00:00
6,989
false
The idea is that C(n,k) = C(n-1, k-1) U n + C(n-1,k), do you get this?\n\n class Solution {\n public:\n vector<vector<int> > combine(int n, int k) {\n \n vector<vector<int> > result;\n if (n < 1 || k <1 || k > n)\n {\n return result;\n }\n \n result = combine(n-1, k-1);\n \n if(result.empty())\n {\n result.push_back(vector<int>{n});\n }\n else\n {\n for (vector<vector<int> >::iterator it = result.begin();\n it!= result.end(); it++)\n {\n it->push_back(n);\n }\n }\n vector<vector<int> > result2 = combine(n-1, k);\n result. insert(result.end(), result2.begin(), result2.end());\n \n return result;\n }\n };
14
0
[]
4
combinations
Simple Java Code with the best explanation
simple-java-code-with-the-best-explanati-yvgh
Java Solution with explanation\n\n\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n\t//declaring new list of list for storing results
Anim3_sh
NORMAL
2023-01-29T05:03:14.158341+00:00
2023-01-31T11:57:19.499720+00:00
2,036
false
***Java Solution with explanation***\n\n```\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n\t//declaring new list of list for storing results\n List<List<Integer>> res = new ArrayList<>();\n\t\t//calling the helper function\n helper(n, k, 1, res, new ArrayList<>());\n return res;\n }\n private void helper(int n, int k, int idex, List<List<Integer>> res, List<Integer> temp){\n\t//when size of the temp list equals to k it is added to the final list \'res\'\n if(temp.size()==k){\n res.add(new ArrayList<>(temp));\n\t\t\t//after adding the temp to res just return \n return;\n }\n\t\t//for loop for iterating over the range [1,n]\n for(int i = idex; i<=n;i++){\n temp.add(i);\n helper(n, k, i+1, res, temp);\n\t\t\t//backtracking to the previous numeber\n temp.remove(temp.size()-1);\n }\n }\n}\n```\n\n***clean code***\n\n\n```\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n\t\n List<List<Integer>> res = new ArrayList<>();\n helper(n, k, 1, res, new ArrayList<>());\n return res;\n }\n private void helper(int n, int k, int idex, List<List<Integer>> res, List<Integer> temp){\n\t\n if(temp.size()==k){\n res.add(new ArrayList<>(temp));\n return;\n }\n\t\t\n for(int i = idex; i<=n;i++){\n temp.add(i);\n helper(n, k, i+1, res, temp);\n temp.remove(temp.size()-1);\n }\n }\n}\n```\n\nPlease upvote if found helpeful:\n\n![image](https://assets.leetcode.com/users/images/22d113b9-360c-44e4-8c8e-fd8d24930ef1_1674968358.456658.jpeg)\n
13
0
['Backtracking', 'Java']
1
combinations
c++ simple solution || using dfs and backtracking
c-simple-solution-using-dfs-and-backtrac-g38u
\nclass Solution {\npublic:\n void solve(vector<vector<int>>& result,int n,int begin ,int k ,vector<int>& combination){\n if(combination.size()==k){\n
yash_pal2907
NORMAL
2021-01-31T16:43:19.241760+00:00
2021-01-31T16:43:19.241806+00:00
1,283
false
```\nclass Solution {\npublic:\n void solve(vector<vector<int>>& result,int n,int begin ,int k ,vector<int>& combination){\n if(combination.size()==k){\n result.push_back(combination);\n return;\n }\n for(int i=begin ; i<=n ;i++){\n combination.push_back(i);\n solve(result , n , i+1 , k , combination);\n combination.pop_back();\n }\n }\n \n vector<vector<int>> combine(int n, int k) {\n vector<int> combination;\n vector<vector<int>> result;\n solve(result , n , 1 , k , combination);\n return result;\n }\n};\n```\n\n**Happy Coding**
13
0
['Backtracking', 'Depth-First Search', 'C']
3
combinations
✅ [C++ , Java , Python] Simple solution with explanation (Backtracking)✅
c-java-python-simple-solution-with-expla-yacg
Intuition\nIt is pretty clear from the constraints that the solution of 2n could work. We could use a backtracking approch in which if we see that the going pat
upadhyayabhi0107
NORMAL
2023-08-01T03:11:41.659712+00:00
2023-08-01T03:13:37.821469+00:00
4,149
false
# Intuition\nIt is pretty clear from the constraints that the solution of 2<sup>n</sup> could work. We could use a backtracking approch in which if we see that the going path doesn\'t leads towards answer we could backtrack.\n<table>\n<tr>\n<th>Input Parameters</th>\n<th>Required time Complexity</th>\n</tr>\n<tr>\n<td> n \u2264 10 </td>\n<td> O(n!) </td>\n</tr>\n<tr>\n<td> n \u2264 20 </td>\n<td> O(2<sup>n</sup>) </td>\n</tr>\n<tr>\n<td> n \u2264 500 </td>\n<td> O(n<sup>3</sup>) </td>\n</tr>\n<tr>\n<td> n \u2264 5000 </td>\n<td> O(n<sup>2</sup>) </td>\n</tr>\n<tr>\n<td> n \u2264 10<sup>6</sup> </td>\n<td> O(n) </td>\n</tr>\n<tr>\n<td> n is large </td>\n<td> O(1) or O(log n) </td>\n</tr>\n</table>\n\n# Approach\n- Base case is when k == 0 or i == n\n - when k == 0 , we fill our ans vector with the vector we\'ve built till now\n - when i == 0 we simply return ;\n- Then it\'s a simple process of take and not take. \n# Complexity\n- Time complexity:O(2<sup>n</sup>)\n\n- Space complexity:O(2<sup>n</sup>)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> ans;\n void dfs(int i , int n , int k , vector<int>& temp){\n if(k == 0){\n ans.push_back(temp);\n return ;\n }\n if(i == n) return ;\n dfs(i + 1 , n , k , temp);\n temp.push_back(i+1);\n dfs(i + 1 , n , k - 1 , temp);\n temp.pop_back();\n }\n vector<vector<int>> combine(int n, int k) {\n vector<int> temp;\n dfs(0 , n , k , temp);\n return ans;\n }\n};\n```\n```Java []\npublic class Solution {\n private List<List<Integer>> ans = new ArrayList<>();\n\n public List<List<Integer>> combine(int n, int k) {\n List<Integer> temp = new ArrayList<>();\n dfs(1, n, k, temp);\n return ans;\n }\n\n private void dfs(int i, int n, int k, List<Integer> temp) {\n if (k == 0) {\n ans.add(new ArrayList<>(temp));\n return;\n }\n if (i > n) return;\n dfs(i + 1, n, k, temp);\n temp.add(i);\n dfs(i + 1, n, k - 1, temp);\n temp.remove(temp.size() - 1);\n }\n}\n```\n```Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def dfs(i, n, k, temp, ans):\n if k == 0:\n ans.append(temp[:])\n return\n if i == n:\n return\n dfs(i + 1, n, k, temp, ans)\n temp.append(i + 1)\n dfs(i + 1, n, k - 1, temp, ans)\n temp.pop()\n\n ans = []\n temp = []\n dfs(0, n, k, temp, ans)\n return ans\n\n```
12
0
['Backtracking', 'C++', 'Java', 'Python3']
0
combinations
JAVA 0ms SOLUTION🔥🚀 || STEP BY STEP EXPLAINED😉😉
java-0ms-solution-step-by-step-explained-68uz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
abhiyadav05
NORMAL
2023-04-29T18:26:46.916577+00:00
2023-04-29T18:26:46.916619+00:00
1,757
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n choose k)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n choose k)\n![Screenshot_20230205_171246.png](https://assets.leetcode.com/users/images/afc6ec07-c724-4ffd-b223-d560f70ca0fe_1682792804.0870206.png)\n\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n ArrayList<Integer> ds = new ArrayList<>();\n List<List<Integer>> ans = new ArrayList<>();\n helper(n, k, 1, ds, ans); // start from 1 instead of 0\n return ans;\n }\n\n public void helper(int n, int k, int start, ArrayList<Integer> ds, List<List<Integer>> ans) {\n if (ds.size() == k) { // add a base case to terminate recursion when the list size reaches k\n ans.add(new ArrayList<>(ds));\n return;\n }\n\n for (int i = start; i <= n; i++) {\n ds.add(i); // add the actual value i to the list instead of the index\n helper(n, k, i + 1, ds, ans); // increment start to i + 1 to avoid duplicates\n ds.remove(ds.size() - 1); // remove the last element to backtrack\n }\n }\n}\n\n```
12
0
['Backtracking', 'Recursion', 'Java']
1
combinations
javascript(DFS)
javascriptdfs-by-yinchuhui88-m359
\nvar combine = function(n, k) {\n let result = [];\n \n function dfs(current, start) {\n if(current.length == k) {\n result.push(cur
yinchuhui88
NORMAL
2018-10-10T06:06:05.315229+00:00
2018-10-10T06:06:05.315271+00:00
1,368
false
```\nvar combine = function(n, k) {\n let result = [];\n \n function dfs(current, start) {\n if(current.length == k) {\n result.push(current);\n return;\n }\n if(current.length > k) {\n return;\n }\n \n for(let i = start; i <= n; i++) {\n dfs(current.concat(i), i + 1);\n }\n \n }\n \n dfs([], 1);\n return result;\n};\n```
12
0
[]
2
combinations
2ms beats 90% Java solution, a small trick to end search early
2ms-beats-90-java-solution-a-small-trick-l4hk
public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> results = new ArrayList<>();\n dfs(1, n, k, new ArrayList<Integer>(), res
kkklll
NORMAL
2016-06-07T17:22:00+00:00
2016-06-07T17:22:00+00:00
2,233
false
public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> results = new ArrayList<>();\n dfs(1, n, k, new ArrayList<Integer>(), results);\n return results;\n }\n \n private void dfs(int crt, int n, int level, List<Integer> comb, List<List<Integer>> results) {\n if (level == 0) {\n List<Integer> newComb = new ArrayList<>(comb);\n results.add(newComb);\n return;\n }\n int size = comb.size();\n for (int i = crt, max = n - level + 1; i <= max; i++) { \n //end search when its not possible to have any combination\n comb.add(i);\n dfs(i + 1, n, level - 1, comb, results);\n comb.remove(size);\n }\n }
12
0
[]
5
combinations
✅Simple C++ Backtracking Solution|90%✅
simple-c-backtracking-solution90-by-xaho-7gf0
Intuition\n Describe your first thoughts on how to solve this problem. \nSimply generate all the subsets but if size execeeds k then return . \n\n# Approach\n D
Xahoor72
NORMAL
2023-01-25T10:01:10.342081+00:00
2023-01-25T10:01:10.342127+00:00
2,660
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimply generate all the subsets but if size execeeds k then return . \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse Backtracking like allother subset problems\n# Complexity\n- Time complexity:$$(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$(2^n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>>ans;\n void backtrack(int n,int start,vector<int>&temp,int k){\n if(temp.size()>k)return;\n if(temp.size()==k)ans.push_back(temp);\n\n for(int i=start;i<=n;i++){\n temp.push_back(i);\n backtrack(n,i+1,temp,k);\n temp.pop_back();\n }\n }\n vector<vector<int>> combine(int n, int k) {\n vector<int>temp;\n backtrack(n,1,temp,k);\n return ans;\n }\n};\n```
11
0
['Backtracking', 'Depth-First Search', 'Recursion', 'C++']
2
combinations
✔️ 100% Fastest Swift Solution
100-fastest-swift-solution-by-sergeylesc-7tp3
\nclass Solution {\n func combine(_ n: Int, _ k: Int) -> [[Int]] {\n var res: [[Int]] = []\n \n \n func backtrack(_ path: [Int],
sergeyleschev
NORMAL
2022-04-06T05:46:41.373520+00:00
2022-04-06T05:46:41.373559+00:00
723
false
```\nclass Solution {\n func combine(_ n: Int, _ k: Int) -> [[Int]] {\n var res: [[Int]] = []\n \n \n func backtrack(_ path: [Int], _ max: Int) {\n if path.count == k {\n res.append(path)\n return\n \n }\n \n var path = path\n if max + 1 > n { return }\n \n for i in max+1...n {\n if n - i < k - path.count - 1 {\n continue\n }\n \n path.append(i)\n backtrack(path, i)\n path.remove(at: path.count - 1)\n }\n }\n \n backtrack([], 0)\n return res\n }\n \n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful.
11
0
['Swift']
2
combinations
Python DFS: solution & visualization step by step
python-dfs-solution-visualization-step-b-py3w
Not the most optimal solution in terms of runtime, but for someone who is learning recursive solutions (such as myself) I hope the visualization is helpful!\n\n
sahn1998
NORMAL
2020-10-01T00:30:57.885927+00:00
2020-10-01T00:38:01.269723+00:00
727
false
Not the most optimal solution in terms of runtime, but for someone who is learning recursive solutions (such as myself) I hope the visualization is helpful!\n```\nclass Solution(object):\n def combine(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n """\n res = []\n self.dfs(n, k, 0, [], res)\n return res\n \n def dfs(self, n, k, start, path, res):\n if len(path) == k:\n res.append(path)\n return None\n \n for index in range(start, n):\n self.dfs(n, k, index+1, path+[index+1], res)\n \n \n \n\'\'\'\ndfs( n = 4, k = 2, start = 0, path = [], res = []) \n| index = 0\n----dfs( n = 4, k = 2, start = 1, path = [1], res = []) \n| | index = 1\n| ----dfs ( n = 4, k = 2, start = 2, path = [1, 2], res = [1, 2]) -> add & return\n| | index = 2\n| ----dfs( n = 4, k = 2, start = 3, path = [1, 3], res = [[1, 2], [1, 3]]) -> add & return\n| | index = 3\n| ----dfs( n = 4, k = 2, start = 4, path = [1, 4], res = [[1, 2], [1, 3], [1, 4]]) -> add & return\n| index = 1\n----dfs( n = 4, k = 2, start = 2, path = [2], res = [[1, 2], [1, 3], [1, 4]]) \n| | index = 2\n| ----dfs ( n = 4, k = 2, start = 3, path = [2, 3], res = [[1, 2], [1, 3], [1, 4], [2, 3]]) -> add & return\n| | index = 3\n| ----dfs( n = 4, k = 2, start = 4, path = [1, 4], res = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4]]) -> add & return\n| index = 2\n----dfs( n = 4, k = 2, start = 3, path = [3], res = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4]]) \n| | index = 3\n| ----dfs ( n = 4, k = 2, start = 4, path = [3, 4], res = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]) -> add & return\n| index = 3\n----dfs( n = 4, k = 2, start = 4, path = [4], res = [[1, 2], [1, 3], [1, 4], [2, 3], [3, 4]]) -> return None\n\'\'\'\n```
11
0
['Backtracking', 'Depth-First Search', 'Recursion', 'Python3']
0
combinations
✅ 🔥 31 ms Runtime Beats 99.45% User🔥|| Code Idea ✅ || Algorithm & Solving Step ✅ ||
31-ms-runtime-beats-9945-user-code-idea-gw5yc
\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Problem Intuition :\n\nGiven two integers n and k, we need to generate all combi
Letssoumen
NORMAL
2024-12-02T03:34:34.391950+00:00
2024-12-02T03:34:34.391988+00:00
1,492
false
![Screenshot 2024-12-02 at 9.00.10\u202FAM.png](https://assets.leetcode.com/users/images/4bb0a89c-db3e-449e-adbd-fbb1ff9eb601_1733110324.038703.png)\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### **Problem Intuition** :\n\nGiven two integers `n` and `k`, we need to generate all combinations of size `k` from numbers in the range `[1, n]`. A combination is a selection of elements without considering the order.\n\n### **Approach** :\n\nThis is a classic **backtracking** problem. The idea is to explore all possible subsets of size `k` using recursion and pruning unnecessary paths.\n\n---\n\n### **Algorithm Steps** :\n\n1. **Initialization**:\n - Create a list to store the final combinations.\n - Start from the first element `1`.\n\n2. **Backtracking Process**:\n - Add elements to a temporary combination.\n - Recursively build the combination by incrementing the start point.\n - Once a combination of size `k` is reached, add it to the result.\n - Backtrack by removing the last element and exploring other paths.\n\n3. **Pruning**:\n - If there are not enough elements left to complete a combination, stop exploring that path.\n\n---\n \n### **Code Implementation** :\n\n#### **C++ Implementation** :\n```cpp\n#include <vector>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination;\n backtrack(1, n, k, combination, result);\n return result;\n }\n \n void backtrack(int start, int n, int k, vector<int>& combination, vector<vector<int>>& result) {\n if (combination.size() == k) {\n result.push_back(combination);\n return;\n }\n \n for (int i = start; i <= n; ++i) {\n combination.push_back(i);\n backtrack(i + 1, n, k, combination, result);\n combination.pop_back();\n }\n }\n};\n```\n\n---\n\n#### **Java Implementation** :\n```java\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n backtrack(1, n, k, new ArrayList<>(), result);\n return result;\n }\n \n private void backtrack(int start, int n, int k, List<Integer> combination, List<List<Integer>> result) {\n if (combination.size() == k) {\n result.add(new ArrayList<>(combination));\n return;\n }\n \n for (int i = start; i <= n; ++i) {\n combination.add(i);\n backtrack(i + 1, n, k, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n\n---\n\n#### **Python 3 Implementation** :\n```python\nclass Solution:\n def combine(self, n: int, k: int):\n result = []\n self.backtrack(1, n, k, [], result)\n return result\n \n def backtrack(self, start, n, k, combination, result):\n if len(combination) == k:\n result.append(combination[:])\n return\n \n for i in range(start, n + 1):\n combination.append(i)\n self.backtrack(i + 1, n, k, combination, result)\n combination.pop()\n```\n\n---\n\n\n\n### **Key Optimizations** :\n\n1. **Pruning**: \n Instead of looping up to `n`, loop until `n - (k - combination.size()) + 1` to avoid unnecessary recursive calls.\n\n2. **Early Stopping**: \n If remaining elements can\'t fulfill the combination size `k`, stop recursion earlier.\n\n---\n\n![image.png](https://assets.leetcode.com/users/images/d0960bde-cc10-42c2-a33e-553e1d570c0d_1733110464.2741654.png)\n
10
0
['Backtracking', 'C++', 'Java', 'Python3']
1
combinations
2 Unique approaches (using String and without it)
2-unique-approaches-using-string-and-wit-3484
Note\n- The string method is very similar to the input-output recursion and backtracking method.\n- Comment down if you want an article on that; it is a useful
quagmire8
NORMAL
2024-03-23T07:31:03.349785+00:00
2024-03-23T09:41:41.225267+00:00
505
false
# Note\n- The string method is very similar to the input-output recursion and backtracking method.\n- Comment down if you want an article on that; it is a useful method for these type of problems.\n- The non-string method follows a simple backtracking approach.\n\n# Intuition\nThe problem involves generating all combinations of size k from the numbers 1 to n. We need to devise a method to efficiently generate these combinations without considering the order of elements.\n\n# Approach\nWe can approach this problem using either a backtracking approach or a string manipulation method. \n\n## Backtracking Approach (Code Snippet 1.1)\nWe can use a recursive backtracking function to generate all combinations. The function `Helper` takes parameters for the current combination (`op`), the starting value for selection (`startVal`), the maximum value (`n`), and the target combination size (`k`). \n- In the base case, if the size of the current combination equals k, we add it to the result vector.\n- In the recursive case, we iterate from the start value to n, selecting each number one by one and recursively calling the function with the updated combination and start value. After the recursive call, we backtrack by removing the last added element.\n\n## String Method (Code Snippet 2)\nThe string method involves representing the numbers 1 to n as a string and manipulating the string to generate combinations. \n- We initialize a string representing the numbers 1 to n.\n- We use a recursive function `Helper` to generate combinations. In each recursive call, we select a character from the string and exclude it from the next recursive call. \n- This method is similar to the input-output recursion and backtracking approach but uses string manipulation instead of directly iterating over numbers.\n\n# Complexity\n- Time complexity: The time complexity for both approaches is O(n choose k), as we need to generate all combinations of size k from n elements.\n- Space complexity: The space complexity depends on the number of valid combinations generated, which is also O(n choose k).\n\n\n# Code Snippet 1.1 (Without String)\n```\nclass Solution {\npublic:\n\n vector<vector<int>> Ans;\n void Helper(vector<int> &op,int startVal,int n,int k){\n\n // base case\n if(op.size() == k){\n Ans.push_back(op);\n return;\n }\n\n // recurisve case\n for(int i=startVal; i<=n; i++){\n\n op.push_back(i);\n // we can also do startVal++ or directly pass ++startVal in the next recursive call\n Helper(op,i+1,n,k);\n op.pop_back(); // backtracking step\n }\n }\n vector<vector<int>> combine(int n, int k) {\n \n vector<int> op;\n int startVal = 1;\n Helper(op,startVal,n,k);\n\n return Ans;\n }\n};\n\n```\n# Code Snippet 1.2 (Without String method but slight variation in the way we increment startVal variable)\n\n```cpp\nclass Solution {\npublic:\n\n vector<vector<int>> Ans;\n void Helper(vector<int> &op,int startVal,int n,int k){\n\n // base case\n if(op.size() == k){\n Ans.push_back(op);\n return;\n }\n\n // recurisve case\n for(int i=startVal; i<=n; i++){\n\n op.push_back(i);\n // we can also do startVal++ or directly pass ++startVal in the next recursive call\n Helper(op,++startVal,n,k);\n op.pop_back(); // backtracking step\n }\n }\n vector<vector<int>> combine(int n, int k) {\n \n vector<int> op;\n int startVal = 1;\n Helper(op,startVal,n,k);\n\n return Ans;\n }\n};\n```\n\n# Code Snippet 2 (String approach)\n```cpp\nclass Solution {\npublic:\n\n /* \n THIS CODE IS FOR GENERATING ALL POSSIBLE COMBINATIONS WHICH WILL COME FROM\n nCk\n */\n \n vector<vector<int>> Ans;\n void Helper(vector<int> &op,string &ip,int k){\n\n // base case\n if(op.size() == k){\n Ans.push_back(op);\n return;\n }\n\n // recursive case\n for(int i=0; i<ip.size(); i++){\n\n op.push_back(ip[i] - \'0\');\n // remember we can make changes in the original input string even if we pass it by value using .erase method\n // pass the next substring after the ith index excuding the current element\n string newIp = ip.substr(i+1);\n Helper(op,newIp,k);\n // backtracking step pop the last element from the op vector after you return from the recursive call\n op.pop_back();\n }\n\n }\n vector<vector<int>> combine(int n, int k) {\n // we will be using the input output string method to generate the combinations\n\n // create the input string\n string ip = "";\n for(int i=1; i<=n; i++) ip.push_back(i + \'0\');\n vector<int> op;\n\n // call the helper function\n Helper(op,ip,k);\n\n return Ans;\n }\n};\n```\n# Feel free to comment down below for any help, Happy Leetcoding !\n\n![Luffy.webp](https://assets.leetcode.com/users/images/65193bac-0a89-4218-be1a-ecfd45e4a3c1_1711178964.141509.webp)\n\n\n\n
9
0
['C++']
2
combinations
C++ Math||DP||unordered_map, map, 4D array
c-mathdpunordered_map-map-4d-array-by-an-tim6
Intuition\n Describe your first thoughts on how to solve this problem. \nHere I provide other idea from backtracking. I prefer to use DP. The backtracking solut
anwendeng
NORMAL
2023-08-01T00:17:45.880748+00:00
2023-08-02T02:32:20.115402+00:00
982
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere I provide other idea from backtracking. I prefer to use DP. The backtracking solution can be used to solve the similar question.\n[46. Permutations\n](https://leetcode.com/problems/permutations/solutions/3850602/cpython-bitmask-backtrackingbeats-100/)\nLet\'s solve it by Math. Consider the set n choose k denoted as\n$$ \nC_k^n=\\{\\{i_1,\\cdots, i_k\\}|1\\leq i_1<\\cdots< i_k\\leq n\\}\n$$\nthen, it follows\n$$\nC_k^n=C_k^{n-1}\\bigcup C_{with\\ n}^n\n$$\nwhere\n$$\nC_{with\\ n}^n=\\{\\{i_1,\\cdots, i_k\\}|1\\leq i_1<\\cdots<i_{k-1}< i_k= n\\}\n$$.\nThe crucial part is that there exists an one-to-one correspondence between the sets $C_{k-1}^{n-1}$ and $C_{with\\ n}^n$ with\n$$\nv\\in C_{k-1}^{n-1} \\longrightarrow v\\cup \\{n \\} \\in C_{with\\ n}^n.\n$$\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse unordered_map( based own hash), recursion with memoization to implement this idea.\n\n2nd version uses map.\n\n3rd version uses 4D array as DP state matrix.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n choose k)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n * k)\n\n# Code\n```\nusing int2=pair<int, int>;\nstruct pair_hash\n{\n size_t operator() (const int2& pair) const {\n return hash<int>()(pair.first) ^ hash<int>()(pair.second);\n }\n};\nclass Solution {\npublic:\n unordered_map<int2, vector<vector<int>>, pair_hash> mp;\n \n vector<vector<int>> comb(int n, int k){\n if (n==1 && k==1) return mp[{1,1}]={{1}};\n if (mp.count({n, k})!=0) return mp[{n, k}];\n vector<vector<int>> ans={};\n if (k==1){\n for(int x=1; x<=n; x++) ans.push_back({x});\n } \n else if (n==k){\n ans.resize(1);\n for(int x=1; x<=n; x++) ans[0].push_back(x);\n }\n else{\n ans=comb(n-1, k);\n vector<vector<int>> c_wo_n=comb(n-1, k-1);\n for (vector<int>& v: c_wo_n){\n vector<int> v_w_n=v;\n v_w_n.push_back(n);\n ans.push_back(v_w_n);\n }\n }\n return mp[{n, k}]=ans;\n }\n vector<vector<int>> combine(int n, int k) {\n return comb(n, k);\n }\n};\n```\n# Code using map is faster for the sake of constraints 1<=k<=n<=20\n```\nclass Solution {\npublic:\n map<int2, vector<vector<int>>> mp;\n \n vector<vector<int>> comb(int n, int k){\n if (n==1 && k==1) return mp[{1,1}]={{1}};\n if (mp.count({n, k})!=0) return mp[{n, k}];\n vector<vector<int>> ans={};\n if (k==1){\n for(int x=1; x<=n; x++) ans.push_back({x});\n } \n else if (n==k){\n ans.resize(1);\n for(int x=1; x<=n; x++) ans[0].push_back(x);\n }\n else{\n ans=comb(n-1, k);\n vector<vector<int>> c_wo_n=comb(n-1, k-1);\n for (vector<int>& v: c_wo_n){\n vector<int> v_w_n=v;\n v_w_n.push_back(n);\n ans.push_back(v_w_n);\n }\n }\n return mp[{n, k}]=ans;\n }\n vector<vector<int>> combine(int n, int k) {\n return comb(n, k);\n }\n};\n```\n# code using 4D array\n```\nclass Solution {\npublic:\n vector<vector<vector<vector<int>>>> dp;\n \n vector<vector<int>> comb(int n, int k){\n if (n==1 && k==1) return dp[1][1]={{1}};\n if (!dp[n][k].empty()) return dp[n][k];\n vector<vector<int>>& ans=dp[n][k];\n if (k==1){\n for(int x=1; x<=n; x++) ans.push_back({x});\n } \n else if (n==k){\n ans.resize(1);\n for(int x=1; x<=n; x++) ans[0].push_back(x);\n }\n else{\n ans=comb(n-1, k);\n vector<vector<int>> c_wo_n=comb(n-1, k-1);\n for (vector<int>& v: c_wo_n){\n vector<int> v_w_n=v;\n v_w_n.push_back(n);\n ans.push_back(v_w_n);\n }\n }\n return ans;\n }\n vector<vector<int>> combine(int n, int k) {\n dp.assign(n+1, vector<vector<vector<int>>>(k+1, vector<vector<int>>()));\n return comb(n, k);\n }\n};\n\n```\n
9
1
['Math', 'Dynamic Programming', 'C++']
0
combinations
Backtracking | Simple | Straightforward
backtracking-simple-straightforward-by-t-krjv
If you find this helpful, do upvote.\n\n\nvar combine = function(n, k) {\n let res = [];\n function backtrack(start = 1, path = []){\n if(path.leng
tusharsheth
NORMAL
2021-12-10T05:01:05.238107+00:00
2021-12-10T05:01:05.238153+00:00
881
false
If you find this helpful, do upvote.\n\n```\nvar combine = function(n, k) {\n let res = [];\n function backtrack(start = 1, path = []){\n if(path.length == k){\n res.push(Array.from(path));\n }else {\n for(let i=start; i<=n; i++){\n path.push(i);\n backtrack(i + 1, path);\n path.pop();\n }\n }\n }\n backtrack();\n return res;\n};\n```
9
0
['Backtracking', 'JavaScript']
0
combinations
Javascript Straightforward Backtracking Solution
javascript-straightforward-backtracking-mrrt8
\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function (n, k) {\n if (n == 1 && k == 1) return [[1]];\n l
tokcao
NORMAL
2020-06-24T20:43:08.169004+00:00
2020-06-24T20:43:08.169034+00:00
1,188
false
```\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function (n, k) {\n if (n == 1 && k == 1) return [[1]];\n let out = [];\n const dfs = (currentSolution, startNumber, out) => {\n if (currentSolution.length == k) out.push(Array.from(currentSolution));\n for (let i = startNumber; i <= n; i++) {\n currentSolution.push(i);\n dfs(currentSolution, i + 1, out);\n currentSolution.pop();\n }\n }\n dfs([], 1, out);\n return out;\n};\n```
9
0
['Backtracking', 'JavaScript']
2
combinations
Time complexity analysis of Backtracking Java
time-complexity-analysis-of-backtracking-ddul
Here is the code, classic dfs backtracing.\n\npublic List<List<Integer>> combine(int n, int k) {\n List<Integer> curr=new ArrayList<Integer>();\n
egg8egg
NORMAL
2019-10-02T17:54:01.772139+00:00
2019-10-02T17:54:01.772195+00:00
1,340
false
Here is the code, classic dfs backtracing.\n```\npublic List<List<Integer>> combine(int n, int k) {\n List<Integer> curr=new ArrayList<Integer>();\n List<List<Integer>> ans =new ArrayList<List<Integer>>();\n dfs(n,k,1,curr,ans);\n return ans;\n }\n \n private void dfs(int n, int k,int next,List<Integer> curr, List<List<Integer>> ans){\n if(curr.size()==k){\n ans.add(new ArrayList(curr));\n return;\n }\n for(int i=next;i<=n;i++){\n curr.add(i);\n dfs(n,k,i+1,curr,ans);\n curr.remove(curr.size()-1);\n }\n }\n```\n\nThere are a lot of different answers for time complexity. Finally I think I got it right and clear, please let me know if you find I got anything wrong.\n\n**First of all, O(2^n) is not tight, O(n!) is not tight. My answer is O(n!/(k-1)!)**\n\nThe simplest way to analysis is that : every round of for loop it will add one and only one number for sure, so how many numbers means how many round of loops, there are k*C(n,k) numbers in the output\n\nso it is O(k*C(n,k)) which is O(n!/(k-1)!)\n\nO(n!/(k-1)!) is not O(n!) because k is not some constant but a input that has impact on time complexity\n\n**Also, I can prove it another way, more acdamic way:**\n\n**Prove: T(n) = n!/(k-1)!**\n\nfrom the dfs we can simply see that\n\n\tT(n) = C1\xA0+\xA0n [(T(n-1)\xA0+ C2]\xA0\xA0 \xA0 \xA0 \xA0\n = nT(n-1)\xA0+ C2*n + C1\n\nwhen you see\xA0T(n) = nT(n-1)..., it usually means n!\n\nbecause \n\n T(0) = 1\n T(n) = nT(n-1)\xA0\xA0 \xA0 \xA0 \xA0 \n = n*[(n-1)*T(n-2)]\xA0 \xA0 \xA0 \xA0 \n\t\t = (n)*(n-1)*(n-2)*(n-3).......T(0)\xA0\xA0 \xA0 \xA0 \xA0 \n\t\t = n!\n\t\t\n**But, here comes the core part of this analysis.**\n```\nif(curr.size()==k){\n ans.add(new ArrayList(curr));\n return;\n }\n```\nbecasue of this part of code, which is the bounding condition of backtracking\n\n\n**the recursive call will only reach kth level of call**\n\nso \n\n\tT(n) = nT(n-1)\xA0\xA0 \xA0 \xA0 \xA0 \n\t\t = n*[(n-1)*T(n-2)]\xA0 \xA0 \xA0 \xA0 \n\t\t = (n)*(n-1)*(n-2)*(n-3)......(n-k)*T(n-k-1)\xA0\xA0 \xA0 \xA0 \xA0 \n\nwhen recrive reach the kth level and try to do T(n-k-1) ```curr.size()==k``` is true, becasue every level curr add one number\n\nT(n-k-1) will simply ``` ans.add(new ArrayList(curr))``` and returns which means T(n-k-1) = 1\n\nso \n\n\tT(n) = (n)*(n-1)*(n-2)*(n-3)......(n-k) * 1\n = n!/(k-1)! \n = k * n!/k! \n\t = k * C(n,k)\n\t\t\t \n\ncompare with n!/(k-1)! , both 2^n and n! are not tight.\n\n
9
0
[]
3
combinations
Recursive Javascript Solution
recursive-javascript-solution-by-gbaik-xkvp
\nfunction combinations(n, k) {\n let result = [];\n\n function traverse(arr, depth) {\n if (arr.length === k) {\n result.push(arr);\n return;\n
gbaik
NORMAL
2017-12-06T23:44:38.242000+00:00
2017-12-06T23:44:38.242000+00:00
1,730
false
```\nfunction combinations(n, k) {\n let result = [];\n\n function traverse(arr, depth) {\n if (arr.length === k) {\n result.push(arr);\n return;\n }\n \n if (depth > n) { \n return;\n }\n\n traverse(arr, depth + 1); \n traverse(arr.concat(depth), depth + 1);\n }\n\n traverse([], 1);\n\n return result;\n}\n```
9
0
['Recursion', 'JavaScript']
0
combinations
ONE LINER BY USING BUILTIN FUNCTIONS AND MANY BEATS THAN SIMPLE BACK TRACING SOLUTIONS
one-liner-by-using-builtin-functions-and-o5q1
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ahsankhalid859
NORMAL
2023-08-07T01:43:26.457304+00:00
2023-08-07T01:43:26.457336+00:00
80
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport itertools\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return list(combinations(range(1,n+1),k))\n```
8
0
['Python3']
1
combinations
python dfs solution - TLE solved for the test case n=20, k=16
python-dfs-solution-tle-solved-for-the-t-nws5
\nclass Solution(object):\n def combine(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n """\n
shuang10
NORMAL
2017-10-10T13:43:08.939000+00:00
2017-10-10T13:43:08.939000+00:00
976
false
```\nclass Solution(object):\n def combine(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n """\n res = []\n if k==0 or n<1:\n return res\n \n self.dfs(n, k, [], res, 1)\n return res\n \n def dfs(self, n, k, path, res, index):\n length = len(path)\n #if len(path) == k:\n if length == k:\n res.append(path[:])\n return\n \n # TLE problem solved by adding this\n if k-length > n - index + 1: # need k numbers in total , still need (k-lenth)\n return\n \n for num in range(index, n+1):\n if num not in path:\n path += [num] \n self.dfs(n, k, path, res, num+1)\n path.pop()\n```
8
0
['Depth-First Search', 'Python']
4
combinations
Easy to understand [C++/Java/python3]
easy-to-understand-cjavapython3-by-sriga-euye
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires finding all possible combinations of k numbers chosen from the ran
sriganesh777
NORMAL
2023-08-01T03:40:09.787453+00:00
2023-08-01T03:40:09.787477+00:00
180
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding all possible combinations of k numbers chosen from the range [1, n]. To solve this, we can use a backtracking approach. The idea is to start with an empty combination and keep adding numbers to it one by one until it reaches the desired length (k).\n\nThe key insight of the backtracking approach is that at each step, we have two choices for the next number to include in the combination:\n\n1. Include the current number in the combination and move forward to explore combinations of length k - 1.\n2. Skip the current number and move forward to explore combinations without it.\n\nBy making these choices recursively, we can generate all valid combinations of k numbers from the range [1, n].\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We start by defining the main combine function that takes two integers n and k as input and returns a list of lists containing all possible combinations of k numbers chosen from the range [1, n].\n\n2. To implement backtracking, we define a recursive helper function, let\'s call it backtrack, which will perform the actual exploration of combinations.\n\nThe backtrack function takes the following parameters:\n\n- start: An integer representing the current number being considered for the combination.\n- curr_combination: A list that holds the current combination being formed.\n- result: The list that will store the final valid combinations.\n4. The base case of the backtrack function is when the length of curr_combination reaches k. This means we have formed a valid combination of length k, so we add it to the result list.\n\n5. Otherwise, if the length of curr_combination is less than k, we proceed with the exploration. For each number i from start to n, we make two choices:\na) Include the number i in the current combination by adding it to curr_combination.\nb) Recur for the next number by calling backtrack(i + 1, curr_combination, result).\n\n6. After making the recursive call, we need to backtrack (undo) the choice we made. Since we are using the same curr_combination list for all recursive calls, we remove the last added element from curr_combination. This ensures that we explore all possible combinations correctly.\n\n7. By following this backtracking process, the backtrack function will explore all possible combinations of length k from the range [1, n], and the valid combinations will be stored in the result list.\n\n8. Finally, we call the backtrack function initially with start = 1, an empty curr_combination, and the result list. This will start the backtracking process and generate all valid combinations.\n\n9. After the backtracking process is complete, the result list contains all the valid combinations, and we return it as the final answer.\n\n# Complexity\n- **Time complexity:** The time complexity of this approach is O(n choose k) since we are generating all possible combinations of k numbers from the range [1, n]. The number of such combinations is (n choose k), which is the total number of elements in the result list.\n\n- **Space complexity:** The space complexity is O(k) since the maximum depth of the recursion (backtracking stack) is k, which represents the length of the combinations we are generating. Additionally, the result list will contain all valid combinations, which can be (n choose k) elements in the worst case.\n\n# Code\n**C++:**\n```\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> curr_combination;\n backtrack(1, n, k, curr_combination, result);\n return result;\n }\n \nprivate:\n void backtrack(int start, int n, int k, vector<int>& curr_combination, vector<vector<int>>& result) {\n if (curr_combination.size() == k) {\n result.push_back(curr_combination);\n return;\n }\n for (int i = start; i <= n; ++i) {\n curr_combination.push_back(i);\n backtrack(i + 1, n, k, curr_combination, result);\n curr_combination.pop_back();\n }\n }\n};\n```\n\n**Java:**\n```\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n List<Integer> curr_combination = new ArrayList<>();\n backtrack(1, n, k, curr_combination, result);\n return result;\n }\n\n private void backtrack(int start, int n, int k, List<Integer> curr_combination, List<List<Integer>> result) {\n if (curr_combination.size() == k) {\n result.add(new ArrayList<>(curr_combination));\n return;\n }\n for (int i = start; i <= n; ++i) {\n curr_combination.add(i);\n backtrack(i + 1, n, k, curr_combination, result);\n curr_combination.remove(curr_combination.size() - 1);\n }\n }\n}\n```\n\n**python3:**\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n result = []\n curr_combination = []\n self.backtrack(1, n, k, curr_combination, result)\n return result\n\n def backtrack(self, start, n, k, curr_combination, result):\n if len(curr_combination) == k:\n result.append(curr_combination[:])\n return\n for i in range(start, n + 1):\n curr_combination.append(i)\n self.backtrack(i + 1, n, k, curr_combination, result)\n curr_combination.pop()\n```\n\n## Please upvote the solution, Your upvote makes my day.\n![upvote img.jpg](https://assets.leetcode.com/users/images/7229039f-8d58-4917-851c-3a97517231fc_1690861201.0607455.jpeg)\n\n
7
0
['Backtracking', 'Recursion', 'C++', 'Java', 'Python3']
1
combinations
C++ || Recursion Backtracking
c-recursion-backtracking-by-abhay5349sin-ggj1
Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\n\nclass Solution {\npublic:\n \n void solve(int n, int k, int num, vector<int>
abhay5349singh
NORMAL
2023-08-01T01:49:06.656382+00:00
2023-08-01T01:49:06.656406+00:00
1,816
false
**Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n```\nclass Solution {\npublic:\n \n void solve(int n, int k, int num, vector<int> &sub_ans, vector<vector<int>> &ans){\n if(k==0){\n ans.push_back(sub_ans);\n return;\n }\n if(num == n+1) return;\n \n // skip\n solve(n,k,num+1,sub_ans,ans);\n \n // acquire\n sub_ans.push_back(num);\n solve(n,k-1,num+1,sub_ans,ans);\n sub_ans.pop_back();\n }\n \n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> sub_ans;\n \n solve(n,k,1,sub_ans,ans);\n \n return ans;\n }\n};\n```
7
1
['Backtracking', 'Recursion', 'C++']
1
combinations
Python simple recursion - 76 ms, faster than 97.09%
python-simple-recursion-76-ms-faster-tha-vmj9
nCk can be constructed through the result of two sub parts:\n1. (n-1)C(k)\n2. (n-1)C(k-1), with n appended to each result.\n\nThe base cases are when n==k and w
udhavsethi
NORMAL
2021-11-15T22:09:05.467466+00:00
2021-11-15T22:09:05.467499+00:00
239
false
*nCk* can be constructed through the result of two sub parts:\n1. *(n-1)C(k)*\n2. *(n-1)C(k-1)*, with *n* appended to each result.\n\nThe base cases are when *n==k* and when *k==1*\n\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n if n == k:\n return [[x for x in range(1,n+1)]]\n if k == 1:\n return [[x] for x in range(1,n+1)]\n # (n-1)C(k-1)\n res = self.combine(n-1, k-1)\n res = [lst + [n] for lst in res]\n # (n-1)C(k)\n res.extend(self.combine(n-1, k))\n return res\n```
7
0
[]
0
combinations
C++ | Backtracking recursion
c-backtracking-recursion-by-pratham7711-bgoa
\nclass Solution {\npublic:\n \n void helper(vector<vector<int>> &res , vector<int>& ans , int n , int left , int k)\n {\n if(k == 0)\n {\n
pratham7711
NORMAL
2021-11-03T22:10:17.641850+00:00
2021-11-03T22:10:17.641892+00:00
925
false
```\nclass Solution {\npublic:\n \n void helper(vector<vector<int>> &res , vector<int>& ans , int n , int left , int k)\n {\n if(k == 0)\n {\n res.push_back(ans);\n return ;\n }\n \n for(int i = left ; i <= n ; i++)\n {\n ans.push_back(i);\n helper(res,ans,n,i+1,k-1);\n ans.pop_back();\n }\n \n }\n \n \n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> res;\n vector<int> ans;\n \n helper(res,ans,n,1,k);\n \n return res;\n \n \n }\n};\n```
7
0
['Recursion', 'C', 'C++']
1
combinations
[C++][Backtracking] - Simple and easy to understand solution
cbacktracking-simple-and-easy-to-underst-x1h2
\nclass Solution {\npublic:\n void backtrack(int n,int k,vector<int> &curr,vector<vector<int> >&ans,int num){\n curr.push_back(num);\n if(curr.
morning_coder
NORMAL
2020-12-05T13:34:56.053815+00:00
2020-12-05T13:34:56.053859+00:00
781
false
```\nclass Solution {\npublic:\n void backtrack(int n,int k,vector<int> &curr,vector<vector<int> >&ans,int num){\n curr.push_back(num);\n if(curr.size()==k){\n ans.push_back(curr);\n curr.pop_back();\n return;\n }\n for(int i=num+1;i<=n;i++){\n backtrack(n,k,curr,ans,i);\n }\n curr.pop_back();\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int> > ans;\n vector<int> curr;\n for(int i=1;i<=n;i++){\n backtrack(n,k,curr,ans,i);\n }\n return ans;\n }\n};\n```
7
0
['Backtracking', 'C', 'C++']
1
combinations
.::Kotlin::. Backtracking
kotlin-backtracking-by-dzmtr-qce4
\n\nclass Solution {\n fun combine(n: Int, k: Int): List<List<Int>> {\n val res = mutableSetOf<List<Int>>()\n \n fun backtrack(j: Int, c
dzmtr
NORMAL
2023-08-01T07:28:36.712146+00:00
2023-08-01T07:28:36.712174+00:00
33
false
\n```\nclass Solution {\n fun combine(n: Int, k: Int): List<List<Int>> {\n val res = mutableSetOf<List<Int>>()\n \n fun backtrack(j: Int, cur: List<Int>) {\n if (cur.size == k) { res += cur; return }\n for (num in j+1..n) backtrack(num, cur + num)\n }\n\n backtrack(0, listOf())\n\n return res.toList()\n }\n}\n```
6
0
['Kotlin']
0
combinations
Python3 one-liner Solution
python3-one-liner-solution-by-motaharozz-xiol
\n\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return combinations(range(1,n+1),k)\n
Motaharozzaman1996
NORMAL
2023-08-01T03:12:51.694812+00:00
2023-08-01T03:12:51.694838+00:00
821
false
\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return combinations(range(1,n+1),k)\n```
6
0
['Python', 'Python3']
2
combinations
2 approaches || easy || short
2-approaches-easy-short-by-kdojha115-0n1t
\nApproach 1:\n\nSimple and fast\n\ncode:\n\nclass Solution\n{\npublic:\n\tvector<vector<int>> combine(int n, int k)\n\t{\n\t\tvector<vector<int>> result;\n\t\t
kdojha115
NORMAL
2022-10-31T18:47:39.034335+00:00
2022-10-31T18:47:39.034376+00:00
1,499
false
\n```Approach 1:```\n\n**Simple and fast**\n\ncode:\n```\nclass Solution\n{\npublic:\n\tvector<vector<int>> combine(int n, int k)\n\t{\n\t\tvector<vector<int>> result;\n\t\tint i = 0;\n\t\tvector<int> p(k, 0);\n\t\twhile (i >= 0)\n\t\t{\n\t\t\tp[i]++;\n\t\t\tif (p[i] > n)\n\t\t\t\t--i;\n\t\t\telse if (i == k - 1)\n\t\t\t\tresult.push_back(p);\n\t\t\telse\n\t\t\t{\n\t\t\t\t++i;\n\t\t\t\tp[i] = p[i - 1];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n};\n```\n\n```Approach 2:```\n\n**using Recursion**\n\ncode:\n\n```\nclass Solution\n{\npublic:\n\tvector<vector<int>> ans;\n\n\tvoid helper(int idx, int k, vector<int> &current, int n)\n\t{\n\t\tif (current.size() == k)\n\t\t{\n\t\t\tans.push_back(current);\n\t\t\treturn;\n\t\t}\n\n\t\tfor (int i = idx; i < n + 1; i++)\n\t\t{\n\t\t\tcurrent.push_back(i);\n\t\t\thelper(i + 1, k, current, n);\n\t\t\tcurrent.pop_back();\n\t\t}\n\t}\n\n\tvector<vector<int>> combine(int n, int k)\n\t{\n\t\tvector<int> current;\n\t\thelper(1, k, current, n);\n\t\treturn ans;\n\t}\n};\n```\nHope it will help you \uD83D\uDE4C.\nThank you!
6
0
['Recursion']
0
combinations
Java solution using backtracking
java-solution-using-backtracking-by-sava-k5n8
\npublic List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> res = new ArrayList();\n combinations(res, new ArrayList<Integer>(), 1,
savan07
NORMAL
2022-06-25T08:17:29.106179+00:00
2022-06-25T08:17:29.106223+00:00
587
false
```\npublic List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> res = new ArrayList();\n combinations(res, new ArrayList<Integer>(), 1, n, k);\n return res;\n }\n private void combinations(List<List<Integer>> res, List<Integer> temp, int start, int end, int k){\n if(k == 0){\n res.add(new ArrayList<Integer>(temp));\n return;\n }\n for(int i=start; i<=end-k+1; i++){\n temp.add(i);\n combinations(res, temp, i+1, end, k-1);\n temp.remove(temp.size()-1);\n }\n }\n```\n**Please upvote if you found the solution helpful**\n*Feel free to ask any questions in the comment section*
6
0
['Backtracking', 'Java']
1
combinations
[JS] Simple Backtracking Solution
js-simple-backtracking-solution-by-js11-xrqj
```\nvar combine = function(n, k) {\n const backtrack = (first = 1, arr = []) => {\n if (arr.length == k) {\n output.push([...arr])\n
js11
NORMAL
2021-11-26T18:07:27.008187+00:00
2021-11-26T18:07:27.008219+00:00
723
false
```\nvar combine = function(n, k) {\n const backtrack = (first = 1, arr = []) => {\n if (arr.length == k) {\n output.push([...arr])\n }\n if (arr.length < k)\n for (let i = first; i <= n; i++) {\n arr.push(i);\n backtrack(i + 1, arr);\n arr.pop();\n }\n }\n\n let output = [];\n backtrack();\n return output;\n};
6
0
['Backtracking', 'JavaScript']
0
combinations
c# solution
c-solution-by-csharp-gqon
```\npublic class Solution {\n private IList> res = new List>();\n \n public IList> Combine(int n, int k) {\n Helper(n, k, 1, new List());\n
csharp
NORMAL
2020-10-31T10:54:51.167626+00:00
2020-10-31T10:54:51.167655+00:00
632
false
```\npublic class Solution {\n private IList<IList<int>> res = new List<IList<int>>();\n \n public IList<IList<int>> Combine(int n, int k) {\n Helper(n, k, 1, new List<int>());\n \n return res;\n }\n \n private void Helper(int n, int k, int i, List<int> l)\n {\n if (l.Count == k)\n res.Add(new List<int>(l));\n else\n for (int j = i; j <= n; j++)\n {\n l.Add(j);\n \n Helper(n, k, j + 1, l);\n \n l.RemoveAt(l.Count - 1);\n }\n }\n}
6
0
[]
1
combinations
JavaScript
javascript-by-doronin-e5ah
\nfunction findCombination(n, k, position, seq, mutRes) {\n if (k === 0) { mutRes.push([...seq]); return; } \n if (position > n) return;\n \n seq.pu
doronin
NORMAL
2020-07-15T20:23:08.702577+00:00
2020-07-15T20:23:08.702605+00:00
733
false
```\nfunction findCombination(n, k, position, seq, mutRes) {\n if (k === 0) { mutRes.push([...seq]); return; } \n if (position > n) return;\n \n seq.push(position);\n findCombination(n, k - 1, position + 1, seq, mutRes);\n seq.pop();\n \n findCombination(n, k, position + 1, seq, mutRes);\n}\n\n\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function(n, k) {\n const mutRes = [];\n findCombination(n, k, 1, [], mutRes)\n return mutRes;\n};\n```
6
1
[]
2
combinations
backtracking python
backtracking-python-by-guopeip0413-eq8p
Hope it helps:\n```\nclass Solution(object):\n def combine(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: List[List[i
guopeip0413
NORMAL
2018-05-15T04:05:29.816184+00:00
2018-05-15T04:05:29.816184+00:00
721
false
Hope it helps:\n```\nclass Solution(object):\n def combine(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n """\n if k>n:\n return []\n ans=[]\n self.helper(n,1,k,ans,[])\n return ans\n \n def helper(self,n,start,k,ans,sub):\n if k==0:\n ans.append(sub[::])\n return\n for i in range(start,n-k+2):\n sub.append(i)\n self.helper(n,i+1,k-1,ans,sub)\n sub.pop()\n\t\t\t\t\t\t
6
1
[]
3
combinations
DFS recursive Java Solution
dfs-recursive-java-solution-by-siyang3-hb41
A DFS idea with back-trace. Very straightforward.\n\n public class Solution {\n public List> combine(int n, int k) {\n List> rslt = new Arr
siyang3
NORMAL
2015-04-01T16:54:46+00:00
2015-04-01T16:54:46+00:00
1,921
false
A DFS idea with back-trace. Very straightforward.\n\n public class Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> rslt = new ArrayList<List<Integer>>();\n dfs(new Stack<Integer>(), 1, n, k, rslt);\n return rslt;\n }\n \n private void dfs(Stack<Integer> path, int index, int n, int k, List<List<Integer>> rslt){\n // ending case\n if(k==0){\n List<Integer> list = new ArrayList<Integer>(path);\n rslt.add(list);\n return;\n }\n // recursion case\n for(int i = index;i <= n;i++){\n path.push(i);\n dfs(path, i+1, n, k-1, rslt);\n path.pop();\n }\n }\n }
6
0
['Depth-First Search', 'Java']
0
combinations
Easy Python recursive solution 64ms
easy-python-recursive-solution-64ms-by-m-g6zm
def combinations(n, k, start=1):\n if k == 1:\n return [[x,] for x in xrange(start, n+1)]\n \n Result = []\n for FirstNum in
metrowind
NORMAL
2015-12-09T22:36:27+00:00
2018-09-16T20:54:45.662124+00:00
1,686
false
def combinations(n, k, start=1):\n if k == 1:\n return [[x,] for x in xrange(start, n+1)]\n \n Result = []\n for FirstNum in xrange(start, n - k + 2):\n for Comb in combinations(n, k-1, FirstNum + 1):\n Result.append([FirstNum,] + Comb)\n return Result
6
0
['Python']
2
combinations
Combinations v.s Combination Sum III (Java)
combinations-vs-combination-sum-iii-java-jhxn
These two questions are very similar, so here I am going to put these two questions into comparisons.\n\nIn Combinations, given k is the length of the sub-list,
issac3
NORMAL
2016-05-23T17:19:11+00:00
2016-05-23T17:19:11+00:00
760
false
These two questions are very similar, so here I am going to put these two questions into comparisons.\n\nIn ***Combinations***, given `k` is the length of the sub-list, `n` is the last number of combination, return all possible combinations of k numbers out of 1 ... n.\n\nIn ***Combination Sum III***, `k` is the length of the sub-list, `n` is the target sum, return all possible combinations of k numbers that add up to `n`. Here, we limit the number used from 1 to 9. \n\nWhat's the similarities? \n\n 1. Both start at `1`\n 2. ***Combinations*** ends ranges from `n - k + 1` to `n` , ***Combination Sum III*** from `1` to `9` \n 3. ***Combinations*** adds sub-list when sub-list size is equal to `k`, ***Combination Sum III*** adds sub-list when sub-list size is equal to `k` and remaining equals `0` (subtract `i` from `n` in loop)\n \n----------\n\n\nCombinations :\n\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> list = new ArrayList<>();\n backtrack(list, new ArrayList<Integer>(), k, 1, n - k + 1);\n return list;\n }\n \n private void backtrack(List<List<Integer>> list, List<Integer> tempList, int k, int start, int end) {\n if (tempList.size() == k) list.add(new ArrayList<>(tempList)); \n else{\n for (int i = start; i <= end; i++) {\n tempList.add(i);\n backtrack(list, tempList, k, i + 1, end + 1);\n tempList.remove(tempList.size() - 1);\n }\n }\n }\n\nCombination Sum III :\n\n public List<List<Integer>> combinationSum3(int k, int n) {\n List<List<Integer>> list = new ArrayList<>();\n backtrack(list, new ArrayList<Integer>(), k, n, 1);\n return list;\n }\n \n private void backtrack(List<List<Integer>> list, List<Integer> tempList, int k, int remain, int start) {\n if(tempList.size() == k && remain == 0) list.add(new ArrayList<>(tempList));\n else{\n for(int i = start; i <= 9; i++) {\n tempList.add(i);\n backtrack(list, tempList, k, remain - i, i + 1);\n tempList.remove(tempList.size() - 1);\n }\n }\n }
6
0
['Backtracking', 'Java']
1
combinations
Efficient and Simple Solution for Combinations
efficient-and-simple-solution-for-combin-ry6d
Problem UnderstandingThe task is to generate all possible combinations of size k from the numbers 1 to n. Each combination should be unique, and the order of th
princesharma21102004
NORMAL
2025-02-01T21:40:24.022611+00:00
2025-02-03T17:46:25.086479+00:00
450
false
# Problem Understanding The task is to generate all possible combinations of size k from the numbers 1 to n. Each combination should be unique, and the order of the numbers in the combination doesn't matter. # Intuition <!-- Describe your first thoughts on how to solve this problem. --> To generate all possible combinations: - Recursion (Backtracking): The solution can be efficiently solved using backtracking. The idea is to start with an empty combination and try adding numbers one by one from 1 to n. Once a combination of size k is formed, we save it. If the current combination size is less than k, we recursively try adding the next number. - Pruning the Search: We need to ensure that once a number is added, we only consider future numbers (to avoid generating duplicate combinations). Hence, the starting number for each recursive call is always greater than the previous one (ensuring the combination is generated in increasing order). # Approach <!-- Describe your approach to solving the problem. --> 1. Backtracking: - Start from an empty combination and try to build it by adding numbers from 1 to n. - If the size of the combination reaches k, we store it in the result. - After adding a number to the combination, recursively continue by calling the function with the next number (num + 1). - If a number doesn’t work out (i.e., you reach a dead-end), backtrack by removing the last added number and trying the next possible number. 2. Recursion & Termination: - The base case is when the size of the combination reaches k, at which point it is added to the results. - Each recursive call adds a number to the combination and continues the process until all valid combinations are found. # Code Walkthrough - The combine function is the entry point that initializes the recursive process and calls the helper function all_combinations. - all_combinations is a recursive helper function that builds the combinations and adds them to combinations once a valid combination of size k is formed. - The start variable ensures that each combination is formed in increasing order, so there are no duplicates. # Complexity - Time complexity: O(nCk) <!-- Add your time complexity here, e.g. $$O(n)$$ --> The number of combinations is represented by the binomial coefficient nCm = n! / (m! * (n - m)!), where n is the total number of elements (from 1 to n), and k is the size of each combination. This represents the total number of combinations that need to be generated, In the worst case, you have to generate all nCm combinations, and each combination is stored as a vector of size k, hence each combination contributes a factor of O(k) to the complexity. - Space complexity: O(K) <!-- Add your space complexity here, e.g. $$O(n)$$ --> The space complexity is determined by the depth of the recursion stack, which at most will be k (since a combination of size k is being constructed). Additionally, we store the combinations, but the space required for storing the result is proportional to the number of combinations, which is already accounted for in the time complexity. ![Screenshot 1946-11-13 at 02.56.30.png](https://assets.leetcode.com/users/images/170d3174-8a6b-42f7-b76a-55dabeee84cf_1738445510.647954.png) # Code ```cpp [] /* AUTHOR - Prince Sharma DATE - 2/2/2025 PROBLEM - Combinations NOTATION - O -> worst case complexcity, S -> for space complexity, T -> for time complexity, C -> combination COMPLEXITY - TO(nCk), SO(k) */ class Solution { public: vector<vector<int>> combine(int n, int k) { vector<int> combination; vector<vector<int>> combinations; all_combinations(n, k, combinations, combination); return combinations; } private: void all_combinations(int& n, int& k, vector<vector<int>>& combinations, vector<int>& combination, int start=1) { if(combination.size()==k) {combinations.emplace_back(combination); return;} for(int num=start; num<=n; num++) { combination.emplace_back(num); all_combinations(n, k, combinations, combination, num+1); combination.pop_back(); } } }; ``` ![99ebb786-8c55-43b7-a8c9-67ad8a9e9b02_1720172878.6942368.webp](https://assets.leetcode.com/users/images/3bd07d1b-467a-4765-a63e-037b68d7e64c_1738445492.6098766.webp)
5
1
['Backtracking', 'C++']
0
combinations
Combinations [C++]
combinations-c-by-moveeeax-xfhn
IntuitionThe problem requires generating all combinations of k numbers from the range [1, n]. This is a classic combinatorial problem that can be efficiently so
moveeeax
NORMAL
2025-01-21T08:23:18.097492+00:00
2025-01-21T08:23:18.097492+00:00
386
false
# Intuition The problem requires generating all combinations of `k` numbers from the range `[1, n]`. This is a classic combinatorial problem that can be efficiently solved using backtracking. # Approach 1. Use a backtracking algorithm to explore all potential combinations: - Start from the first number and attempt to include it in the current combination. - Move to the next number, recursively building the combination until its size equals `k`. - Backtrack by removing the last added number and proceed to explore the next options. 2. Stop exploring further when the combination's size reaches `k` and add it to the result. # Complexity - **Time complexity**: $$O(\binom{n}{k})$$ Each valid combination is constructed once, and there are $$\binom{n}{k}$$ combinations in total. - **Space complexity**: $$O(k)$$ The maximum depth of the recursion stack is `k`, and we also use a temporary vector of size `k` during construction. # Code ```cpp class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> result; vector<int> combination; backtrack(1, n, k, combination, result); return result; } void backtrack(int start, int n, int k, vector<int>& combination, vector<vector<int>>& result) { if (combination.size() == k) { result.push_back(combination); return; } for (int i = start; i <= n; ++i) { combination.push_back(i); backtrack(i + 1, n, k, combination, result); combination.pop_back(); } } }; ```
5
0
['C++']
0
combinations
✅BEST SOLUTION | BACKTRACKING | JAVA | EXPLAINED🔥🔥🔥
best-solution-backtracking-java-explaine-7wl2
Approach:\nEmploys a backtracking approach to explore all possible combinations.\nThe backtrack function recursively constructs combinations:\nBase case: If the
AdnanNShaikh
NORMAL
2024-09-09T16:06:26.062891+00:00
2024-09-09T16:06:26.062926+00:00
748
false
**Approach:**\nEmploys a backtracking approach to explore all possible combinations.\nThe backtrack function recursively constructs combinations:\nBase case: If the current combination\'s size equals k, add it to the result list.\nFor each number from start to n:\nAdd the number to the current combination.\nRecursively call backtrack with the updated combination and starting index.\nRemove the last added number to explore other possibilities.\n\n**Time Complexity: O(n choose k)**\nThe number of combinations is given by the binomial coefficient (n choose k), which grows exponentially with n and k.\n\n**Space Complexity: O(k)**\nThe recursion stack can reach a depth of k in the worst case, leading to O(k) space complexity.\n\n**Explanation:**\nThe code effectively leverages backtracking to explore all possible combinations. The backtrack function recursively adds numbers to the current combination and explores different possibilities by backtracking and removing numbers. The base case ensures that combinations of size k are added to the result list.\n\n# Code\n```java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n backtrack(result, new ArrayList<>(), 1, n, k);\n return result;\n }\n \n private void backtrack(List<List<Integer>> result, List<Integer> tempList, int start, int n, int k) {\n // If the combination is done (i.e., we\'ve picked k numbers)\n if (tempList.size() == k) {\n result.add(new ArrayList<>(tempList)); // Add a copy of the current combination to the result list\n return;\n }\n \n // Try all numbers from \'start\' to \'n\'\n for (int i = start; i <= n; i++) {\n tempList.add(i); // Pick the number\n backtrack(result, tempList, i + 1, n, k); // Recursively pick the next number\n tempList.remove(tempList.size() - 1); // Remove the last picked number to try another possibility\n }\n }\n}\n```
5
0
['Java']
1