Combinations

Combinations

问题:

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

思路:

  dfs + 回溯

我的代码:

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        if(n <= 0 || k == 0 || k > n) return rst;
        List<Integer> list = new ArrayList<Integer>();
        int num = 1;
        int[] nums = new int[n];
        for(int i = 0; i < n; i++)
            nums[i] = num++;
        helper(list, nums, 0, 0, n, k);
        return rst;
    }
    private List<List<Integer>> rst = new ArrayList<List<Integer>>();
    public void helper(List list, int[] nums, int start, int count, int n, int k)
    {
        if(count == k)
        {
            rst.add(new ArrayList(list));
            return;
        }
        for(int i = start; i < n; i++)
        {
            list.add(nums[i]);
            helper(list, nums, i + 1, count + 1, n, k);
            list.remove(list.size() - 1);
        }
    }
}
View Code

学习之处:

  • 常见的dfs+回溯模板
  • 九皇后问题,Permutation,Solve Sudoku,Combination Sum,Combination Sum II 都属于该类问题。

回溯模板:

void dfs()
{
    if()
    {
           if(之前的情况都满足要求了)
                record()
           return;                  
    }
    for(所有情况)
     {
            当前情况符合要求
            dfs()//剩余的情况是否也可以呢,递归去判断去吧?
            不采用当前情况    
     }                   
}    

代码执行过程是二叉树的遍历,例如在所有的情况里面 只要两种情况的压栈,弹栈的执行过程。


原文地址:https://www.cnblogs.com/sunshisonghit/p/4323125.html