Combinations

https://leetcode.com/problems/combinations/

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],

]

解题思路:

最基本的组合题目,DFS+回溯,遇到了去重,解决方法也比较基本。现在写起来轻松多了。

public class Solution {

    public List<List<Integer>> combine(int n, int k) {

        List<List<Integer>> result = new LinkedList<List<Integer>>();

        List<Integer> current = new LinkedList<Integer>();

        int[] dict = new int[n];

        for(int i = 0; i < n; i++){

            dict[i] = i + 1;

        }

        dfs(result, current, dict, k, 0);

        return result;

    }

    

    public void dfs(List<List<Integer>> result, List<Integer> current, int[] dict, int k, int step){

        if(current.size() == k){

            result.add(new LinkedList(current));

            return;

        }

        

        for(int i = step; i < dict.length; i++){

            current.add(dict[i]);

            dfs(result, current, dict, k, i + 1);

            current.remove(current.size() - 1);

        }

    }

}

 

 

你可能感兴趣的:(com)