随笔 - 128  文章 - 0  评论 - 1  阅读 - 40740

组合生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// C# program to find
// combinations from n
// arrays such that one
// element from each
// array is present
using System;
using System.Collections.Generic;
class GFG{
 
// Function to print combinations
// that contain one element from
// each of the given arrays
static void print(List<int> []arr)
{
// Number of arrays
int n = arr.Length;
 
// To keep track of next
// element in each of
// the n arrays
int []indices = new int[n];
 
// Initialize with first
// element's index
for(int i = 0; i < n; i++)
    indices[i] = 0;
 
while (true)
{
    // Print current combination
    for(int i = 0; i < n; i++)
    Console.Write(arr[i][indices[i]] + " ");
     
    Console.WriteLine();
 
    // Find the rightmost array
    // that has more elements
    // left after the current
    // element in that array
    int next = n - 1;
    while (next >= 0 &&
        (indices[next] + 1 >=
        arr[next].Count))
    next--;
 
    // No such array is found
    // so no more combinations left
    if (next < 0)
    return;
 
    // If found move to next
    // element in that array
    indices[next]++;
 
    // For all arrays to the right
    // of this array current index
    // again points to first element
    for(int i = next + 1; i < n; i++)
    indices[i] = 0;
}
}
 
// Driver code
public static void Main(String[] args)
{
// Initializing a vector
// with 3 empty vectors
List<int> []arr = new List<int>[3];
for(int i = 0; i < arr.Length; i++)
    arr[i] = new List<int>();
 
// Now entering data
// [[1, 2, 3], [4], [5, 6]]
arr[0].Add(1);
arr[0].Add(2);
arr[0].Add(3);
arr[1].Add(4);
arr[2].Add(5);
arr[2].Add(6);
 
print(arr);
}
}
 
// This code is contributed by shikhasingrajput

  

posted on   wakaka_wka  阅读(80)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示