每日一题(回溯)

①、题目

饼干:

力扣icon-default.png?t=M666https://leetcode.cn/problems/assign-cookies/

路径:

力扣icon-default.png?t=M666https://leetcode.cn/problems/all-paths-from-source-to-target/


②、解题

饼干:

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        //尽量满足胃口小的小孩,并在此基础上尽量用小的饼干
        Arrays.sort(g);
        Arrays.sort(s);
        int answer=0;
        
        for (int i=0,j=0; i < g.length && j < s.length; j++) {
            if (g[i]<=s[j]){
                answer++;
                i++;
            }
        }
        
    return answer;
    }
}

 路径:

class Solution {
    private int[][] graph;
    private List<List<Integer>> answer=new ArrayList<>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        this.graph=graph;
        ArrayList<Integer> list = new ArrayList<>();
        list.add(0);
        dfc(0,list);
        return answer;
    }

    private void dfc(int a,List<Integer> temp){
        //来到第n-1个节点:满足,终止
        if (a==graph.length-1)
            //不能直接将temp添加,否则此后temp变化,answer里面也跟着变
            //因为二者指向同一个地址
            answer.add(new ArrayList<Integer>(temp));

        for (int i = 0; i < graph[a].length; i++) {
            temp.add(graph[a][i]);
            dfc(graph[a][i],temp);
            //回溯:
            temp.remove(temp.size()-1);

        }

    }
}

③、运行截图

 

 


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
回溯算法是一种常用的搜索算法,通常用于解决组合问、排列问、选择问等。下面是一个使用C++语言实现的回溯算法示例,用于求解1~n的排列组合问: ```c++ #include <iostream> using namespace std; const int N = 10; int n; // n个数 int nums[N]; // 数组存储1~n的数 bool used[N]; // 标记数字是否已被选中 int path[N]; // 存储当前排列组合的结果 void backtrack(int depth) { if (depth == n) { // 排列组合完成,输出结果 for (int i = 0; i < n; i++) { cout << path[i] << " "; } cout << endl; return; } for (int i = 0; i < n; i++) { if (!used[i]) { // 如果数字i未被选中 path[depth] = nums[i]; // 将数字i加入当前排列组合 used[i] = true; // 标记数字i已被选中 backtrack(depth + 1); // 递归搜索下一层 used[i] = false; // 回溯到上一层,将数字i标记为未被选中 } } } int main() { cin >> n; for (int i = 0; i < n; i++) { nums[i] = i + 1; } backtrack(0); return 0; } ``` 在该程序中,我们使用`backtrack`函数实现回溯算法。该函数的参数`depth`表示当前排列组合的深度,初始值为0,表示从第一个位置开始排列组合。当`depth`等于`n`时,表示排列组合完成,输出结果。 在每一层循环中,我们枚举当前可选的数字,如果数字`i`未被选中,则将其加入当前排列组合,并标记为已被选中。然后递归搜索下一层,完成搜索后回溯到上一层,将数字`i`标记为未被选中,以便在后续搜索中重新使用。 该算法的时间复杂度为O(n!),因为总共有n个数字,每个数字有n-1个可选位置,所以排列组合的总数为n * (n-1) * (n-2) * ... * 1 = n!。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦鱼yx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值