首页 > 其他 > 详细

Leetcode 1079 活字印刷 回溯

时间:2021-04-19 11:08:32      阅读:14      评论:0      收藏:0      [点我收藏+]

技术分享图片

  回溯解法,JAVA:

 public final int numTilePossibilities(String tiles) {
        Set<String> set = new HashSet<String>();
        search(tiles.toCharArray(), "", tiles.length(), set);
        return set.size();
    }

    public final void search(char[] chars, String ans, int len, Set<String> set) {
        if (len < 0) return;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ‘0‘) continue;
            char his = chars[i];
            chars[i] = ‘0‘;
            String next = ans + his;
            if (!set.contains(next)) set.add(next);
            search(chars, next, len - 1, set);
            chars[i] = his;
        }
    }

  JS:

/**
 * @param {string} tiles
 * @return {number}
 */
var numTilePossibilities = function (tiles) {
    let mySet = new Set();
    search(tiles.split(""), "", tiles.length, mySet);
    return mySet.size;
};

var search = function (arr, ans, len, mySet) {
    if (len < 0) return;
    for (let i = 0; i < arr.length; i++) {
        if (!arr[i]) continue;
        let his = arr[i];
        arr[i] = 0;
        mySet.add(ans + his);
        search(arr, ans + his, len - 1,mySet);
        arr[i] = his;
    }
}

 

Leetcode 1079 活字印刷 回溯

原文:https://www.cnblogs.com/niuyourou/p/14675079.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!