Leetcode-backtracking题目总结

Leetcode-78. Subsets  (全组合问题)

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Input: nums = [1,2,3] Output:[[3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]]

public List> subsets(int[] nums) {
    List> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, 0);
    return list;
}

private void backtrack(List> list , List tempList, int [] nums, int start){
    list.add(new ArrayList<>(tempList));
    for(int i = start; i < nums.length; i++){
        tempList.add(nums[i]);
        backtrack(list, tempList, nums, i + 1);
        tempList.remove(tempList.size() - 1);
    }
}

如果是全排列问题:

public List> fullsubsets(int[] nums) {
    List> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums);
    return list;
}

private void backtrack(List> list , List tempList, int [] nums){
    list.add(new ArrayList<>(tempList));
    for(int i = 0; i < nums.length; i++){
        if(!tempList.contains(nums[i])){
            tempList.add(nums[i]);
            backtrack(list, tempList, nums);
            tempList.remove(tempList.size() - 1);
        }
    }
}

Leecode-79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false

不利用额外空间的方法:

public boolean exist(char[][] board, String word) {
    char[] w = word.toCharArray();
    for (int y=0; y

使用了额外空间的方法:

  boolean backtrack(char[][]board, boolean[][]visited, String word, int index, int x, int y){
        if(index == word.length()) return true;
        if(x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y]) return false;
        if(word.charAt(index) != board[x][y]) return false;
        visited[x][y] = true;
        boolean res = backtrack (board, visited, word, index + 1, x, y + 1)
                    || backtrack(board, visited, word, index + 1, x, y - 1)
                    || backtrack(board, visited, word, index + 1, x + 1, y)
                    || backtrack(board, visited, word, index + 1, x - 1, y);
        visited[x][y] = false;
        return res; 
    }

    public boolean exist(char[][] board, String word) {
        boolean[][] visited = new boolean[board.length][board[0].length];
        for(int i = 0; i < board.length; ++i) {
            for (int j = 0; j < board[0].length; ++j) {
                if (backtrace(board,visited, word ,0, i, j))
                    return true;
            }
        }
        return false;
    }

 

你可能感兴趣的:(leetcode,算法,笔试面试题)