道阻且长,行则将至,走慢一点没关系,不停下就|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

LeetCode216.组合总数III

代码1(自己)

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(k, n, 1);
        return res;
    }
    public void backtracking(int k, int n, int startIndex) {
        if (path.size() == k) {
            if (getSum(path) == n) {
                res.add(new ArrayList<>(path)); 
                //return;         
            }
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) {
            path.add(i);
            backtracking(k, n, i + 1);
            path.remove(path.size() - 1);
        }
    }
    public int getSum(List<Integer> path) {
        int sum = 0;
        for (int i = 0; i < path.size(); i ++) {
            sum += path.get(i);
        }
        return sum; 
    }
}

剪枝操作: for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) {}

代码2(代码随想录)

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(k, n, 0, 1);
        return res;
    }
    public void backtracking(int k, int n, int sum, int startIndex) {
        if (path.size() == k) {
            if (sum == n) {
               res.add(new ArrayList<>(path)); 
            }
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i ++) {
            sum += i; // 处理
            path.add(i); // 处理
            backtracking(k, n, sum, i + 1); // 回溯
            sum -= i; // 撤销
            path.remove(path.size() - 1); // 撤销
        }
    }
}

注意:

恢复现场

处理过程和回溯过程是一一对应的,处理过程中有加法操作,回溯过程就要有对应的减法操作。

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/16276066.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(12)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.