Leetcode 77. Combinations
Description:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Thinking:
Combination problems means we should consider the duplicate since combination doesn't care about the order.So we need to use a int pos
as a parameter in the helper function.
Complexity:
The time complexity is approximately n!.
Steps:
- check whether input is valid.
- create the helper function and decide which parameters we need and the condition that we can return
Code:
public class Solution { public List<List<Integer>> combine(int n, int k) { if(n < k) return new ArrayList<List<Integer>>(); List<List<Integer>> result = new ArrayList<>(); List<Integer> list = new ArrayList<>(); combineHelper(result, list, n, k, 1); return result; } public void combineHelper(List<List<Integer>> result, List<Integer> list, int n, int k, int pos){ if(list.size() == k){ result.add(new ArrayList<Integer>(list)); return; } if(pos > n){ return; } for(int i = pos; i <= n; i++){ list.add(i); combineHelper(result, list, n, k, i+1); list.remove(list.size()-1); } } }
Conclusion:
This can be a template for the problem of combination.