Leetcode 77. Combinations

stuff about computer science and programming
Post Reply
User avatar
dendiz
Site Admin
Posts: 234
Joined: Wed Oct 10, 2018 3:48 am

Leetcode 77. Combinations

Post by dendiz » Tue Feb 12, 2019 5:01 am

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Code: Select all

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
image_1548886059.png
(this image was made by someone on the leetcode discussion forums)

Code: Select all

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        f(result, new ArrayList(), n, k, 1);
        return result;
    }
    
    void f(List<List<Integer>> result, List<Integer> temp, int n, int k, int s) {
        if (temp.size() == k) {
            result.add(new ArrayList<Integer>(temp));
            return;
        } else {
            for(int i=s;i<=n;i++) {
                temp.add(i);
                f(result, temp, n, k, i + 1);
                temp.remove(temp.size() - 1);
            }
        }
    }
}

Post Reply