剑指offer 2021/7/27

43 篇文章 0 订阅
27 篇文章 0 订阅

38. 字符串的排列

代码:

回溯。

class Solution {
    LinkedList<String> res = new LinkedList<>();
    char[] c;
    public String[] permutation(String s) {
        c = s.toCharArray();
        backtrack(0);
        return res.toArray(new String[0]);
    }
    public void backtrack(int x){
        if(x == c.length - 1){
            res.add(String.valueOf(c));
            return;
        }
        HashSet<Character> set = new HashSet<>();
        for(int i = x; i < c.length; ++i){
            if(set.contains(c[i])){
                continue;
            }
            set.add(c[i]);
            swap(x, i);
            backtrack(x+1);
            swap(x,i);
        }
    }
    public void swap(int a, int b){
        char temp;
        temp = c[a];
        c[a] = c[b];
        c[b] = temp;
    }
}

17. 打印从1到最大的n位数

代码:

回溯。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    LinkedList<List<Integer>> list = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        dfs(root, target);
        return list;
    }
    public void dfs(TreeNode node, int target){
        if(node == null)    return;
        path.add(node.val);
        target -= node.val;
        if(target == 0 && node.left == null && node.right == null){
            list.add(new LinkedList(path));
        }
        dfs(node.left, target);
        dfs(node.right, target);
        path.pollLast();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值