[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/feinibuai/JavaArithmetic/master/src/LeetCode/LeetCode279_no.java [Back]  [Original]

package LeetCode;

import javafx.util.Pair;

import java.util.LinkedList;

public class LeetCode279_no {

    // 279. Perfect Squares
    // https://leetcode.com/problems/perfect-squares/description/
    //  Time Limit Exceeded  Memory Limit Exceeded
    //
    // : O(2^n)
    // : O(2^n)
    public int numSquares(int n) {

        LinkedList queue = new LinkedList();
        queue.addLast(new Pair(n, 0));

        while (!queue.isEmpty()) {
            Pair front = queue.removeFirst();
            int num = front.getKey();
            int step = front.getValue();

            if (num == 0)
                return step;

            for (int i = 1; num - i * i >= 0; i++)
                queue.addLast(new Pair(num - i * i, step + 1));
        }

        throw new IllegalStateException("No Solution.");
    }

    // visited,
    // : O(n)
    // : O(n)
    public int numSquares2(int n) {

        LinkedList queue = new LinkedList();
        queue.addLast(new Pair(n, 0));

        boolean[] visited = new boolean[n + 1];
        visited[n] = true;

        while (!queue.isEmpty()) {
            Pair front = queue.removeFirst();
            int num = front.getKey();
            int step = front.getValue();

            if (num == 0)
                return step;

            for (int i = 1; num - i * i >= 0; i++)
                if (!visited[num - i * i]) {
                    queue.addLast(new Pair(num - i * i, step + 1));
                    visited[num - i * i] = true;
                }
        }

        throw new IllegalStateException("No Solution.");
    }

    // : O(n)
    // : O(n)
    public int numSquares3(int n) {

        if (n == 0)
            return 0;

        LinkedList queue = new LinkedList();
        queue.addLast(new Pair(n, 0));

        boolean[] visited = new boolean[n + 1];
        visited[n] = true;

        while (!queue.isEmpty()) {
            Pair front = queue.removeFirst();
            int num = front.getKey();
            int step = front.getValue();

            if (num == 0)
                return step;

            for (int i = 1; num - i * i >= 0; i++) {
                int a = num - i * i;
                if (!visited[a]) {
                    if (a == 0) return step + 1;
                    queue.addLast(new Pair(num - i * i, step + 1));
                    visited[num - i * i] = true;
                }
            }
        }

        throw new IllegalStateException("No Solution.");
    }

    public static void main(String[] args) {

        System.out.println((new LeetCode279_no()).numSquares(12));
        System.out.println((new LeetCode279_no()).numSquares(13));
    }
}

Web Proxy Viewer  |  New URL  |  Original Page