leetcode77.组合Java

LeetCode.77 组合

leetcode77.组合Java_第1张图片

解法一:DFS+回溯法

图解:
leetcode77.组合Java_第2张图片

代码:

package com.leetcode.solution;

import java.util.*;

/**
 * @Author : fanc
 * @Date : 2019-09-01 19:25
 */
public class Solution77 {
    List<List<Integer>> output = new LinkedList<>();
    int n;
    int k;

    public void traceback(int first, LinkedList<Integer> current) {
        if (current.size() == k) {
            //错误,不能直接加上current,否则所有的元素都是一个引用
            //output.add(current);
            output.add(new LinkedList<Integer>(current));
            System.out.println(output);
            return;
        }

        for (int i = first; i <= n; i ++) {
            //保存回溯结果
            //LinkedList temp = new LinkedList<>(current);
            current.add(i);
            traceback(i + 1, current);
            //回溯:第一种方法current.removeLast()因为每一个add后面跟一个remove保证回溯
            //current = temp;
            current.removeLast();
        }
    }

    public List<List<Integer>> combine(int n, int k) {
        this.n = n;
        this.k = k;
        traceback(1, new LinkedList<>());
        return output;
    }
}

有两种回溯方法:

  1. 保存current结果
  2. add之后然后remove,保证一对一

需要注意的是,需要每次new一个list,防止每一个引用都一样,也就是需要有一个深拷贝的过程

你可能感兴趣的:(java)