Recursion

经典题目

78 Subsets

	/*
		Method 1 : Recursion
		
		Do recursion based on index
		For each index, we have two choices:
			1. append the current num to list
			2. do nothing.
	*/
public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> cur = new ArrayList<>();
    helper(nums, 0, cur, ans);
    return ans;
}
private void helper(int[] nums, int index, List<Integer> cur, List<List<Integer>> ans) {
    if (index == nums.length) {
        ans.add(new ArrayList<>(cur));
        return;
    }
    // Choice 1: don't append current num
    helper(nums, index + 1, cur, ans);
		// Choice 2: append current num
    cur.add(nums[index]);
    helper(nums, index + 1, cur, ans);
		// backtrack
    cur.remove(cur.size() - 1);
}

Eight Queens (CC189) 51 N-Queens

Towers of Hanoi (CC189)

In the classic problem of the Tower of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints: 1) Only one disk can be moved at a time. 2) A disk is slid off the top of one tower onto another tower 3) A disk cannot be placed on top of a smaller disk. Write a program to move the disks from the first tower to the last using stacks.

Boolean Evaluation (CC189)

Given a boolean expression consisting of the symbols 0 (false), 1 (true), & (AND), | (OR), and ^ (XOR), and a desired boolean result value result, implement a function to count the number of ways of parenthesizing the expression such that it evaluates to result. The expression should be fully parenthesized (e.g., (0) ^ (1)) but not extraneously (e.g., ((0) ^ (1))).

884 Decoded String at Index

679 24 Game

Last updated