A simple java solution


  • 0
    L

    A simple java solution

    
    public List<Integer> diffWaysToCompute(String input) {
            String[] nums = input.split("[+*-]");
            List<Integer> op = new ArrayList<Integer>();
            List<Integer> res = new ArrayList<Integer>();
            for (char c : input.toCharArray())
                if (c == '+' || c == '-' || c == '*')
                    op.add(c == '+' ? 0 :(c == '-' ? 1 : 2));
            return aux(nums, op, 0, nums.length - 1);
        }
    
    private List<Integer> aux(String[] nums, List<Integer> op, int i, int j) {
        List<Integer> res = new ArrayList<Integer>();
        if (i == j)
            res.add(Integer.parseInt(nums[i]));
        else if (i < j)
            for (int k = i; k < j; k++)
                for (int left : aux(nums, op, i, k))
                    for (int right : aux(nums, op, k + 1, j))
                        res.add(op.get(k) == 0 ? left + right : (op.get(k) == 1 ? left - right : left * right));
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.