zoukankan      html  css  js  c++  java
  • BackTracking_Fixed sum for array elements

    Given an array a contains distinct positive integers, count how many combinations of integers in a add up to exactly sum

    For example, given int[] a = {11, 3, 8} ; and sum = 11

    You should output 2, because 11 == 11 and 3 + 8 == 11

    This is typically a backtracking problem

    Enumerate all the subsets of the given array to see how many of them match the condition

    when you write backtracking procedure using recursion, please be careful of which condition do you

    use to terminate the loop, in this code snippet, there two conditions,

    1. sum == 0

    2. t == a.Length

    and when t == a.Length, we might be got an solution yet, don't forget this case.

    Backtracking

    Code

    recursive way

    Code

    C法

    #include<stdio.h>
    #include<stdlib.h>
    
    int count = 0; // number of solutions
    
    /*
     * array - positive numbers
     * n     - element count in array
     * sum   - pair of sum
     * t     - recursion deep
     */
    void find_combinations(int *array, int n, int sum, int t) {
        if (t == n) {
            if (sum == 0) {
                count++;
            }
            return;
        }
    
        if (sum == 0) { // Find a solution
            count++;
        }
        else {
            if (sum >= array[t]) {  // left tree
                find_combinations(array, n, sum - array[t], t + 1);
            }
            if (sum > 0) {                  // right tree
                find_combinations(array, n, sum, t + 1);
            }
        }
    }
    
    int main(void) {
        int a[] = {11, 3, 8, 4, 1, 7};
        find_combinations(a, 6, 11, 0);
        printf("%d\n", count);
    
        system("pause");
        return 0;
    }

    ==

     

  • 相关阅读:
    win10下以管理员身份打开hosts文件
    使用Dockerfile构建镜像命令自己的理解
    我们在删除镜像的时候被告知有容器正在使用,可是容器已经被停止了
    Docker构建镜像过于缓慢解决-----Docker构建服务之部署和备份jekyll网站
    VMware虚拟机ubuntu显示屏幕太小解决办法
    树莓派3B从装系统到安装RYU过程
    树莓派3b 换国内源 更新源
    Raspbain系统无屏幕无网线通过ssh远程连接树莓派设置wifi步骤
    Mplayer 隐藏边框和显示位置的方法
    使用mplayer查看摄像头
  • 原文地址:https://www.cnblogs.com/graphics/p/1495466.html
Copyright © 2011-2022 走看看