• <BackTracking> Combination, DFS :216 DP: 377


    216. Combination Sum III

    保证subset.size( ) == k && target == 0的时候结束DFS

    subset.size( ) > k || target < 0返回。

    class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res = new ArrayList<>();
            if(k <= 0 || n < 1) return res;
            dfs(res, new ArrayList<Integer>(), k, n, 1);
            return res;
        }
        
        private void dfs(List<List<Integer>> res, List<Integer> subset, int k, int target, int index){
            if(subset.size() > k && target < 0)
                return;
            if(subset.size() == k && target == 0){
                res.add(new ArrayList<Integer>(subset));
                return;            
            }
            for(int i = index; i <= 9; i++){
                subset.add(i);
                dfs(res, subset, k, target - i, i + 1);
                subset.remove(subset.size() - 1);
            }
        }
    }

    377. Combination Sum IV

    DFS: 此方法超时

    class Solution {
        int count;
        public int combinationSum4(int[] nums, int target) {
            if(nums == null || nums.length == 0) return 0;
            dfs(nums, target, new ArrayList<Integer>());
            return count;
        }
        
        private void dfs(int[] nums, int target, List<Integer> subset){
            if(target == 0){
                count++;
                return;
            }
            if(target < 0){
                return;
            }
            for(int i = 0; i < nums.length; i++){
                subset.add(nums[i]);
                dfs(nums, target - nums[i], subset);
                subset.remove(subset.size() - 1);
            }
        }
    }

    DP: i - nums[ j ]表 当前nums[ j ]与之前comb[ ] 中的组合数字继续组合得到target。

    class Solution {
        public int combinationSum4(int[] nums, int target) {
            int[] comb = new int[target + 1];
            comb[0] = 1;
            for(int i = 1; i < comb.length; i++){
                for(int j = 0; j < nums.length; j++){
                    if(i - nums[j] >= 0){
                        comb[i] += comb[i - nums[j]];
                    } 
                }
            }
            return comb[target];
        }
    }
  • 相关阅读:
    基于MINA实现server端心跳检测(KeepAliveFilter)
    TCP的TIME_WAIT快速回收与重用
    HDU4183 起点到终点再到起点 除起点每点仅经过一次 网络流
    oracle union 注入工具
    sqlmap注入技巧收集
    sqlmap的一些小技巧
    FCKeditor漏洞利用
    WAF绕过的技巧
    杨辉三角
    Oracle 常用入侵命令
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11909259.html
Copyright © 2020-2023  润新知