Print ways to obtain given sum by repeated throws of a dice
Last Updated :
12 Jan, 2022
Given an integer N, the task is to print the ways to get the sum N by repeatedly throwing a dice.
Input: N = 3
Output:
1 1 1
1 2
2 1
3
Explanation: The standard dice has 6 faces i.e, {1, 2, 3, 4, 5, 6}. Therefore the ways of getting sum 3 after repeatedly throwing a dice are as follows:
1 + 1 + 1 = 3
1 + 2 = 3
2 + 1 = 3
3 = 3
Input: N = 2
Output:
1 1
2
Approach: This problem can be solved by using Recursion and Backtracking. The idea is to iterate for every possible value of dice i in the range [1, 6] and recursively call for the remaining sum i.e, (N – i) and keep appending the value of the current dice value in a data structure like strings. If the required sum is zero, print the elements in the stored string.
Below is the implementation of the above approach
C++
#include <iostream>
using namespace std;
void printWays( int n, string ans)
{
if (n == 0) {
for ( auto x : ans) {
cout << x << " " ;
}
cout << endl;
return ;
}
else if (n < 0) {
return ;
}
for ( int i = 1; i <= 6; i++) {
printWays(n - i, ans + to_string(i));
}
}
int main()
{
int N = 3;
printWays(N, "" );
return 0;
}
|
Java
import java.util.*;
public class GFG {
static void printWays( int n, String ans)
{
if (n == 0 ) {
for ( int i = 0 ; i < ans.length(); i++) {
System.out.print(ans.charAt(i) + " " );
}
System.out.println();
return ;
}
else if (n < 0 ) {
return ;
}
for ( int i = 1 ; i <= 6 ; i++) {
printWays(n - i, ans + Integer.toString(i));
}
}
public static void main(String args[])
{
int N = 3 ;
printWays(N, "" );
}
}
|
Python3
def printWays(n, ans):
if n = = 0 :
for x in range ( len (ans)):
print (ans[x], end = " " )
print ("")
return
elif n < 0 :
return
for i in range ( 1 , 7 ):
printWays(n - i, ans + str (i))
N = 3
printWays(N, "")
|
C#
using System;
using System.Collections;
class GFG {
static void printWays( int n, string ans)
{
if (n == 0) {
for ( int i = 0; i < ans.Length; i++) {
Console.Write(ans[i] + " " );
}
Console.WriteLine();
return ;
}
else if (n < 0) {
return ;
}
for ( int i = 1; i <= 6; i++) {
printWays(n - i, ans + i.ToString());
}
}
public static void Main()
{
int N = 3;
printWays(N, "" );
}
}
|
Javascript
<script>
function printWays(n, ans)
{
if (n == 0) {
for (let x = 0; x < ans.length; x++) {
document.write(ans[x] + " " );
}
document.write( '<br>' )
return ;
}
else if (n < 0) {
return ;
}
for (let i = 1; i <= 6; i++) {
printWays(n - i, ans + (i).toString());
}
}
let N = 3;
printWays(N, "" );
</script>
|
Time Complexity: O(6N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...