Ayush-Tibrewal / LEETCODE---Java-Solutions-

0 stars 0 forks source link

DYNAMIC PROGRAMMING #5

Open Ayush-Tibrewal opened 4 months ago

Ayush-Tibrewal commented 4 months ago

image

public void sub(int index, int[] arr1, List<Integer> arr2) {
    int n = arr1.length;
    if (index >= n) return; // base case

    // don't take the current element
    sub(index + 1, arr1, arr2);

    // add the current element to the array
    arr2.add(arr1[index]);
    sub(index + 1, arr1, arr2);

    // remove the current element from the array
    arr2.remove(arr2.size() - 1);
}

image

Counting of the total number of ways

public class SubsetGenerator {
    public int sub(int index, int[] arr1, List<Integer> arr2) {
        int n = arr1.length;
        if (index >= n) {
            return 1;
        }
        // Don't take the current element
       int l = sub(index + 1, arr1, arr2);

        // Add the current element to the list
        arr2.add(arr1[index]);
       int r = sub(index + 1, arr1, arr2);

        // Remove the current element from the list
        arr2.remove(arr2.size() - 1);
        return l+r;
    }
Ayush-Tibrewal commented 4 months ago

ist 2nd problem image