How to Generate All k‑Number Combinations from 1 to n in Java (with Interview Tips)
This article shares practical interview communication advice and demonstrates a Java backtracking solution that enumerates every possible k‑element combination within the range [1, n] using pruning for efficiency.
Interview Communication Tips
Technical candidates often fail interviews due to ineffective self‑presentation. Common issues and corrective actions:
Over‑explaining: Avoid teaching the interviewer; instead, frame your experience as a solution to the problem they care about.
Lack of structured storytelling: Connect projects with a clear narrative that highlights strategic thinking and impact.
Nervousness: Practice speaking in meetings and conduct regular mock interviews to improve composure under pressure.
Inappropriate attitude: Maintain confidence without arrogance and avoid excessive timidity.
Insufficient role knowledge: Research the target position and tailor answers to match the employer’s requirements.
Problem: Generate All k‑Element Combinations
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. The order of the combinations does not matter.
Example 1
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4]
]Example 2
Input: n = 1, k = 1
Output: [[1]]Solution Idea
Use depth‑first search (backtracking) with pruning. At each recursion level, iterate the next candidate number from start up to n - k + 1 to guarantee enough remaining numbers for a complete combination. When k reaches zero, add the current list to the result.
Java Implementation
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtrack(n, k, 1, new ArrayList<>());
return ans;
}
private void backtrack(int n, int k, int start, List<Integer> path) {
if (k == 0) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = start; i <= n - k + 1; i++) {
path.add(i);
backtrack(n, k - 1, i + 1, path);
path.remove(path.size() - 1);
}
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
