首页 > 8.23 老虎2题
头像
来一个offer就躺平
编辑于 2020-08-23 18:44
+ 关注

8.23 老虎2题

第一题 奇偶排队

    public static ListNode lineUp(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode single = head;
        ListNode doublePre = head.next;
        ListNode doubleAfter = head.next;
        while (single != null && doubleAfter != null) {
            single.next = doubleAfter.next;
            single = single.next;
            doubleAfter.next = single.next;
            doubleAfter = doubleAfter.next;
        }
        single.next = doublePre;
        return head;
    }

第二题回溯 拿到数组要排个序

    public ArrayList<ArrayList<Integer>> combinationSum (int[] prices, int m) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if(prices == null || prices.length == 0 || m <= 0){
            return result;
        }
        Arrays.sort(prices);
        ArrayList<Integer> list = new ArrayList<>();
        combination(result, list, prices, m, 0);
        return result;
    }
    public void combination(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] prices, int target, int index){
        if(target <= 0){
            if(target == 0){
                result.add(new ArrayList<>(list));
            }
            return;
        }
        for(int i = index; i < prices.length; i++){
            list.add(prices[i]);
            combination(result, list, prices, target - prices[i], i + 1);
            list.remove(list.size() - 1);
        }
    }

全部评论

(0) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

历年真题 真题热练榜 24小时
技术(软件)/信息技术类
查看全部

近期精华帖

热门推荐