C语言版输入两个整数 n 和 sum,从数列1, 2, 3, ... , n 中 随意取几个数,使其和等于 sum,要求将其中所有的可能组合列出来

题目的意思:

从1到n中随机选取几个数,让其和等于m根据这句话,选出来的数不能重复,但是选取的个数任意

所以可以利用深度优先搜索DFS+回溯来解决

其中深度优先搜索算法用来寻找所有可能的组合,而回溯是用来筛选出所有可能组合中的可行解【如果发现某候选解不是可行解,直接丢弃】

注:由于选出来的数不能重复,所以在进行深搜时,下一次深搜应是从当前元素的下一个元素继续往后看

步骤:

1.从第一个元素开始相加

2.让局部和继续累加候选的剩余值

3.局部和等于目标值,保存组合,向上回退,寻找其它组合

//
// Created by gxj on 2021-11-29.
//
#include <stdio.h>

int list[100]={0};
int rent[100][100]={0};
int top1 = -1;
int top2 = -1;

int len(int *num){
    int count =0;
    while((num+count) != NULL && *(num+count) != 0)
        count++;
    return count;
}

void dfs(int index, int n, int count){
    if(count == 0) {
        top2++;
        for(int i=0; i<= top1; i++){
            rent[top2][i] = list[i];
        }
    }else {
        for (int i = index; i <= count && i <= n; i++) {
            list[++top1]=i;
            dfs(i + 1,n,count - i);
            top1--;
        }
    }
}

int main()
{
    fflush(stdout);
    printf("请输入数字n和m:\n");
    int n, m;
    scanf("%d%d",&n,&m);
    dfs(1, n, m);
    if(top2!=-1){
        for(int i=0; i<= top2; i++){
            int length = len(rent[i]);
            printf("长度:%d\n", length);
            if(length > 0){
                for(int j=0;j<length;j++){
                    printf("%d\t", rent[i][j]);
                }
                printf("\n");
            }
        }
    }
    return 0;
}

// n=5 m=5
    //数列:1,2,3,4,5
    // 从1开始深搜:
    //   1<5 -> 1+2<5 -> 1+2+3>5【丢弃3,且不再 在1+2+3的基础上继续深搜】 -> 1+2+4>5【丢弃4,且不再 在1+2+4的基础上继续深搜】 -> 1+2+5>5【丢弃5,且不再 在1+2+5的基础上继续深搜】 -> 丢弃2【1+2的深搜完毕】
    //       -> 1+3<5 -> 1+3+4>5【丢弃4,且不再 在1+3+4的基础上继续深搜】 -> 1+3+5>5【丢弃5,且不再 在1+3+5的基础上继续深搜】 -> 丢弃3【1+3的深搜完毕】
    //       -> 1+4==5【找到一种组合,存入最终结果】 ->丢弃4【1+4的深搜完毕】
    //       -> 1+5>5【丢弃5,1+5的深搜完毕】
    //       -> 丢弃1【1的深搜完毕】
    // 从2开始深搜:
    //   2<5 -> 2+3==5【找到一种组合,存入最终结果】 -> 丢弃3【2+3的深搜完毕】
    //       -> 2+4>5【丢弃4,2+4的深搜完毕】
    //       -> 2+5>5【丢弃5,2+5的深搜完毕】
    //       -> 丢弃2【2的深搜完毕】
    // 从3开始深搜:
    //   3<5 -> 3+4>5【丢弃4,3+4的深搜完毕】
    //       -> 3+5>5【丢弃5,3+5的深搜完毕】
    //       -> 丢弃3【3的深搜完毕】
    // 从4开始深搜:
    //   4<5 -> 4+5>5【丢弃5,4+5的深搜完毕】
    //       -> 丢弃4【4的深搜完毕】
    // 从5开始深搜:
    //    5==5【找到一种组合,存入最终结果】
    //       -> 丢弃5【5的深搜完毕】
    //数列1到5已遍历完毕
    //最终结果:[[1,4],[2,3],[5]]

效果如图

 原文链接:https://blog.csdn.net/ty6693/article/details/98310846

猜你喜欢

转载自blog.csdn.net/gxy03/article/details/121601362